import on from 'ember-evented/on';
import computed from 'ember-computed';
import Service from 'ember-service';
import { A as emberA } from 'ember-array/utils';
import injectService from 'ember-service/inject';

export default Service.extend({
  store: injectService(),
  isLoading: false,
  all: null,
  pending: computed.filterBy('all', 'isPending'),
  isNotificationsCountLoading: computed.none('notificationsCount'),
  notificationsCount: null,

  setDefaults: on('init', function() {
    this.set('all', emberA());
  }),

  _query(params={}) {
    let store = this.get('store');
    return store.query('friends-list-request', params);
  },

  _queryRecord(params={}) {
    let store = this.get('store');
    return store.queryRecord('friends-list-request', params);
  },

  display(count) {
    let all = this.get('all'),
        displayed = this.get('displayed'),
        addedCount = 0;

    for (let i=0; i<all.length; i++) {
      let request = all[i];

      if (addedCount === count) {
        return addedCount;
      }

      if (request.get('isPending') && !displayed.includes(request)) {
        addedCount++;
        displayed.addObject(request);
      }
    }

    return addedCount;
  },

  fetchFirstPage() {
    if (this.get('_promise')) {
      return this.get('_promise');
    }
    return this.fetchNewRequests();
  },

  fetchNewRequests(params) {
    let promise = this.fetch(params);
    this.set('_promise', promise);
    return promise;
  },

  fetch(params) {
    this.set('isLoading', true);

    return this._query(params).then(requests => {
      this.get('all').addObjects(requests);
      this.set('isLoading', false);
    });
  },

  fetchNotificationCount() {
    return this._query({
      type: 'count-notifications'
    }).then(results => {
      let notificationsCount = results.get('meta.notifications-count') || 0;
      this.set('notificationsCount', notificationsCount);
      return notificationsCount;
    });
  },

  clearNotificationsCount() {
    if (!this.get('notificationsCount')) {
      return;
    }

    this.set('notificationsCount', 0);
    return this._query({ type: 'clear-notifications' });
  },

  accept(request) {
    return this._queryRecord({ request, type: 'accept' });
  },

  reject(request) {
    return this._queryRecord({ request, type: 'reject' });
  }
});
