/* globals Twitch */

import Component from 'ember-component';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import { API_VERSION } from 'web-client/models/deprecated-stream';
import InteractivityDeferredComponent from 'web-client/mixins/interactivity-deferred-component';

export default Component.extend(InteractivityDeferredComponent, {
  api: injectService(),
  communityService: injectService('community'),
  session: injectService(),
  tracking: injectService(),

  classNames: ['ct-spotlight-container'],
  channels: [],
  game: null,
  hero: null,
  streams: [],
  community: null,
  canGenerateClips: computed.readOnly('session.isAuthenticated'),

  isLoggedIn: computed(function () {
    return Twitch.user.isLoggedIn();
  }),

  shouldRender: computed('streams.length', 'community.isCommunity', function () {
    let streams = this.get('streams');
    let community = this.get('community');
    return !!streams.length && (!community || community.get('isCommunity'));
  }),

  spotlightAutoplay: computed(function () {
    let spotlightAutoplay = Twitch.storage.getObject('spotlightAutoplay');
    return spotlightAutoplay !== null ? spotlightAutoplay : true;
  }),

  shouldStartPaused: computed('isLoggedIn', 'spotlightAutoplay', function () {
    return this.get('isLoggedIn') && !this.get('spotlightAutoplay');
  }),

  didReceiveAttrs() {
    this._super(...arguments);
    let channels = this.get('channels');
    if (channels) {
      this._setStreamsByChannels(channels);
    }
    if (!this.get('spotlightAutoplay')) {
      this.trackStickyPause();
    }
  },

  _setStreamsByChannels(channels) {
    let gameName = this.get('game.name');
    let community = this.get('community');
    let channelParam = channels.join(',');
    let url = `streams?game=${gameName}&limit=100&channel=${channelParam}`;

    this.get('api').request('get', url, { version: API_VERSION }).then(response => {
      if (this.isDestroyed) {
        return;
      }
      let streams = [];
      if (response && response.streams) {
        let communityService = this.get('communityService');
        streams = (!community ? response.streams : response.streams.filter(stream => communityService.hasCommunityTag(community, stream.channel.status)))
          .sort((a, b) => channels.indexOf(a.channel.name) - channels.indexOf(b.channel.name))
          .slice(0, 4)
          .map(stream => {
            // stream.id must match channel.name so that the twitch-player2 works
            stream.id = stream.channel.name;
            stream.tags = communityService.extractFromTags(stream.channel.status);
            return stream;
          });
      }
      this.setProperties({
        'streams': streams,
        'hero': streams.length ? streams[0] : null
      });
      if (this.get('shouldRender')) {
        this.trackChannels();
      }
    });
  },

  trackStickyPause() {
    this.get('tracking').trackEvent({ event: 'carousel_paused_on_load' });
  },

  trackChannels() {
    let data = {
      community: this.get('community.name'),
      // Default slot vaules, which get set if the slot was filled
      'carousel_slot_0_channel': null,
      'carousel_slot_1_channel': null,
      'carousel_slot_2_channel': null,
      'carousel_slot_3_channel': null
    };
    let streams = this.get('streams');
    if (streams) {
      streams.forEach((stream, index) => {
        data[`carousel_slot_${index}_channel`] = stream.id;
      });
    }
    this.get('tracking').trackEvent({ event: 'carousel_display_creative', data });
  },

  trackHeroChange() {
    let data = {
      community: this.get('community.name'),
      channel: this.get('hero.id')
    };
    this.get('tracking').trackEvent({ event: 'carousel_change_hero', data });
  },

  actions: {
    setHero(hero) {
      this.set('hero', hero);
      this.trackHeroChange();
    },

    videoPaused() {
      if (this.get('isLoggedIn')) {
        Twitch.storage.setObject('spotlightAutoplay', false);
        this.set('spotlightAutoplay', false);
      }
    },

    videoPlayed() {
      if (this.get('isLoggedIn')) {
        Twitch.storage.setObject('spotlightAutoplay', true);
        this.set('spotlightAutoplay', true);
      }
    },

    videoPlayerContentShowing() {
      this.reportInteractive();
    }
  }
});
