import Adapter from 'ember-data/adapter';
import injectService from 'ember-service/inject';


export default Adapter.extend({
  api: injectService(),

  createRecord (store, type, snapshot) {
    let postId = snapshot.record.get('postId');
    let channelName = snapshot.record.get('channelName');
    let url = `feed/${channelName}/posts/${postId}/comments`;
    let payload = {content: snapshot.attr('body')};

    return this.get('api').authRequest('post', url, payload);
  },

  deleteRecord (store, type, snapshot) {
    let channelName = snapshot.record.get('post.user.login');
    let commentId = snapshot.record.get('id');
    let postId = snapshot.record.get('post.id');
    let url = `feed/${channelName}/posts/${postId}/comments/${commentId}`;

    return this.get('api').authRequest('del', url);
  },

  query (store, type, params) {
    if (params.type === 'queryComments') {
      return this._queryComments(...arguments);
    } else if (params.type === 'deleteUserCommentsFromPost') {
      return this._deleteUserCommentsFromPost(...arguments);
    }
    throw new Error('query must have a type');
  },

  _queryComments (store, type, params) {
    let channelName = params.channelName;
    let postId = params.postId;
    let url = `feed/${channelName}/posts/${postId}/comments`;
    let payload = {
      limit: params.limit || 10,
      cursor: params.cursor
    };

    return this.get('api').authRequest('get', url, payload);
  },

  _deleteUserCommentsFromPost (store, type, snapshot) {
    let comment = snapshot.comment;
    let post = snapshot.post;
    let postId = post.get('id');
    let channelName = post.get('user.login');
    let user = comment.get('user.login');
    let url = `feed/${channelName}/posts/${postId}/comments`;

    return this.get('api').authRequest('del', url, { user });
  }
});
