/* globals Twitch */
import Component from 'ember-component';
import injectService from 'ember-service/inject';
import SendRouteActionMixin from 'web-client/mixins/send-route-action';

let streamIds = {}; // used for hiding duplicate streams

export default Component.extend(SendRouteActionMixin, {
  communities: injectService(),
  streams: [],
  isLoading: true,

  init() {
    this._super(...arguments);

    this.set('streams', []);
    streamIds = {};

    this.set('communities.offset', 0);
    this.get('communities').getStreamsForCommunity(this.get('communities.communityInfo._id')).then((data) => {
      if (this.isDestroyed) { return; }
      this.addUniqueStreams(data.streams);
      this.set('isLoading', false);
    });
    Twitch.tracking.funnel.trackPageView({location: 'community'});
  },

  addUniqueStreams(streams) {
    streams.forEach(stream => {
      if (!streamIds[stream.channel._id]) {
        streamIds[stream.channel._id] = true;
        this.get('streams').pushObject(stream);
      }
    });
    this.set('streamIds', streamIds);
  },

  actions: {
    loadMoreStreams() {
      this.get('communities').fetchMoreStreams(this.get('communities.communityInfo._id')).then((data) => {
        if (this.isDestroyed) { return; }
        this.addUniqueStreams(data.streams);
      });
    }
  }
});
