import Component from 'ember-component';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';

export default Component.extend({
  store: injectService(),
  communities: null,
  game: null,
  isLoading: false,
  sortBy: null,

  hasMoreCommunities: computed('communities.length', 'communities.meta.total', function () {
    let total = this.get('communities.meta.total');
    let current = this.get('communities.length');
    return current < total;
  }),

  filteredCommunities: computed('communities.[]', function () {
    let communities = this.get('communities');
    return communities ? communities.filterBy('isCommunity') : [];
  }),

  init() {
    this._super(...arguments);
    if (!this.get('sortBy')) {
      this.set('sortBy', 'viewers');
    }
    if (!this.get('communities')) {
      let game = this.get('game.name');
      if (game) {
        let sortBy = this.get('sortBy');
        this.set('isLoading', true);
        this.get('store').query('community', { game, sortBy, limit: 100 })
          .then(communities => {
            if (this.isDestroyed) { return; }
            this.set('communities', communities);
          })
          .finally(() => {
            if (this.isDestroyed) { return; }
            this.set('isLoading', false);
          });
      }
    }
  },

  actions: {
    loadMore() {
      let communities = this.get('communities');
      if (communities && this.get('hasMoreCommunities')) {
        let game = this.get('game.name');
        let offset = this.get('communities.length');
        let sortBy = this.get('sortBy');
        this.get('store').query('community', { game, offset, sortBy, limit: 100 })
          .then(newCommunities => {
            if (this.isDestroyed) { return; }
            this.get('communities').pushObjects(newCommunities.get('content'));
          });
      }
    }
  }
});
