import Adapter from 'ember-data/adapter';
import { RECENT_FEED_ID, NEWSFEED_ID } from 'web-client/services/feeds';

import injectService from 'ember-service/inject';

const DEFAULT_FETCH_LIMIT = 10;

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

  // TODO: Remove, see https://git-aws.internal.justin.tv/web/web-client/issues/698
  shouldReloadAll() {
    return true;
  },

  findRecord () {
  },

  createRecord (store, type, snapshot) {
    let user = snapshot.belongsTo('user');
    let userName = user.attr('login');

    let url = `feed/${userName}/posts`;

    let payload = {
      content: snapshot.attr('body'),
      share: snapshot.record.get('twitterShare')
    };

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

  updateRecord () {
  },

  deleteRecord (store, type, snapshot) {
    let user = snapshot.belongsTo('user');
    let userName = user.attr('login');
    let postId = snapshot.record.get('id');
    let url = `feed/${userName}/posts/${postId}`;

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

  findAll () {
  },

  query (store, type, params) {
    if (!params.feed){
      throw new Error("query must have a `feed`");
    }

    if (params.feed === RECENT_FEED_ID) {
      return this._queryRecentFeed(...arguments);
    }

    if (params.feed === NEWSFEED_ID) {
      return this._queryNewsfeed(...arguments);
    }

    return this._queryFeed(...arguments);
  },

  _queryRecentFeed(store, type, params) {
    let url = "feed/recent";
    let requestParams = {
      limit: params.limit || 10,
      cursor: params.cursor
    };

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

  _queryNewsfeed(store, type, params) {
    let url = 'feed/posts';
    let requestParams = {
      limit: params.limit || DEFAULT_FETCH_LIMIT,
      cursor: params.cursor
    };

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

  _queryFeed(store, type, params) {
    let url = `feed/${params.feed}/posts`;

    let requestParams = {
      limit: params.limit || 10,
      cursor: params.cursor
    };

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

  queryRecord (store, type, query) {
    let userName = query.feed;
    let id = query.id;
    let url = `feed/${userName}/posts/${id}`;

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

  findMany () {
  }
});
