import Component from 'ember-component';
import { routes } from 'web-client/utilities/friends-list/settings';
import { truncateInteger } from 'web-client/utilities/friends-list/computed';
import injectService from 'ember-service/inject';
import { A as emberA } from 'ember-array/utils';

const DISPLAY_LIMIT = 10;

export default Component.extend({
  store: injectService(),
  requests: injectService('twitch-friends-list/requests'),
  pubsub: injectService('twitch-friends-list/pubsub'),
  requestsRoute: routes.requests,
  requestsCount: truncateInteger('requests.pending.length', 20),
  displayedRequests: null,

  init() {
    this._super(...arguments);
    this.get('requests').fetchFirstPage().then(this.displayRequests.bind(this));
    this.set('displayedRequests', emberA());
    this.get('pubsub').on('requestedMessage', this, 'requestHandler');
  },

  _display(count) {
    let displayed = this.get('displayedRequests'),
        pending = this.get('requests.pending'),
        addedCount = 0;

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

      if (addedCount === count) {
        return addedCount;
      }
      if (!displayed.includes(request)) {
        addedCount++;
        displayed.addObject(request);
      }
    }

    return addedCount;
  },

  _removeRequest(request) {
    this.get('displayedRequests').removeObject(request);
    this.updateDisplayedRequests();
  },

  updateDisplayedRequests() {
    this.sortDisplayedRequests();
    this._display(DISPLAY_LIMIT - this.get('displayedRequests.length'));
  },

  strangerSort(f1, f2) {
    return f1.get('isStranger') - f2.get('isStranger');
  },

  sortDisplayedRequests() {
    let pending = this.get('requests.pending');
    pending.sort(this.strangerSort);
  },

  requestHandler() {
    if (!this.get('isOpen')) {
      this.incrementProperty('requests.notificationsCount');
      this.get('requests').fetchNewRequests();
    } else {
      this.refreshRequests(); // Could debounce this in the future to handle many incoming requests
    }
  },

  willDestroy() {
    this.get('pubsub').off('requestedMessage', this, 'requestHandler');
    this._super(...arguments);
  },

  displayRequests() {
    this.get('requests').clearNotificationsCount();
    this.updateDisplayedRequests();
  },

  refreshRequests() {
    this.get('requests').fetchNewRequests().then(this.displayRequests.bind(this));
  },

  actions: {
    onResolve(request) {
      this.runTask(() => {
        this._removeRequest(request);
      }, 500);

      // Refresh the friends to get the updated presence, including the new friend that was just accepted
      this.get('store').query('friends-list-user', {
        type: 'friends'
      });
    }
  }
});
