/* globals i18n */

import Route from 'ember-route';
import { isEmpty } from 'ember-utils';
import injectService from 'ember-service/inject';

export default Route.extend({
  navigation: injectService(),
  communities: injectService(),

  isInteractive(interactiveComponents) {
    if (this.get('controller.noLiveChannels')) {
      return interactiveComponents['beacon:directory-community-no-live-channels'];
    }
    return interactiveComponents['directory-community'];
  },

  activate: function () {
    this.get('navigation').setSelected('Communities');
  },

  buildPageTitle() {
    return {title: i18n('All Communities')};
  },

  setupController: function (controller) {
    let communities = controller.get('communities');

    if (!isEmpty(communities)) {
      return;
    }

    let options = {kind: 'top', limit: 40};

    this.store.query('twitch-community', options).then(results => {
      if (this.isDestroyed) { return; }
      this.set('cursor', results.meta.cursor);
      communities.pushObjects(results.toArray());
    });
  },

  actions: {
    loadMoreTopCommunities: function () {
      if(this.get('cursor')) {
        let communities = this.get('controller.communities');
        let options = {kind: 'top', limit: 30, cursor: this.get('cursor')};
        this.store.query('twitch-community', options).then(results => {
          if (this.isDestroyed) { return; }
          this.set('cursor', results.meta.cursor);

          results.forEach(community => {
            if (!communities.includes(community)) {
              communities.pushObject(community);
            }
          });
        });
      }
      return;
    }
  }
});
