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

//
// This is the minimum amount to fetch to determine if they have >20
// pending requests.
//
const DEFAULT_LIMIT = 21;

export default Adapter.extend({
  friendship: injectService('twitch-friends-list/backend/friendship'),

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

  createRecord(store, type, snapshot) {
    let friendId = snapshot.attr('friendId'),
        friendLogin = snapshot.attr('friendLogin'),
        isRecommended = snapshot.attr('isRecommended'),
        url = `/requests/${friendLogin}`;

    return this.get('friendship').request(url, {
      type: 'PUT',
      data: {is_recommended: isRecommended}
    }).then(() => {
      return {
        action: 'friend',
        params: {
          friendId,
          is_recommended: isRecommended
        }
      };
    });
  },

  queryCountNotifications() {
    return this.get('friendship').request('/notifications');
  },

  queryClearNotifications() {
    let url = '/notifications';
    return this.get('friendship').request(url, { type: 'DELETE' });
  },

  queryRequests(store, type, params={}) {
    let data = { limit: params.limit || DEFAULT_LIMIT };

    return this.get('friendship').request('/requests', { data });
  },

  query(store, type, params={}) {
    switch (params.type) {
      case 'count-notifications':
        return this.queryCountNotifications(...arguments);
      case 'clear-notifications':
        return this.queryClearNotifications(...arguments);
      default:
        return this.queryRequests(...arguments);
    }
  },

  queryRecordAccept(store, type, params) {
    let friendId = params.request.get('friendId'),
        friendLogin = params.request.get('friendLogin'),
        url = `/${friendLogin}`;

    return this.get('friendship').request(url, {
      type: 'PUT'
    }).then(() => {
      return {
        action: 'accept',
        params: { friendId }
      };
    });
  },

  queryRecordReject(store, type, params) {
    let friendId = params.request.get('friendId'),
        friendLogin = params.request.get('friendLogin'),
        url = `/requests/${friendLogin}`;

    return this.get('friendship').request(url, {
      type: 'DELETE'
    }).then(() => {
      return {
        action: 'reject',
        params: { friendId }
      };
    });
  },

  queryRecord(store, type, params) {
    switch (params.type) {
      case 'accept':
        return this.queryRecordAccept(...arguments);
      case 'reject':
        return this.queryRecordReject(...arguments);
      default:
        throw new Error('must specify { type: "accept|reject" } when calling queryRecord');
    }
  }
});
