/* globals Twitch */
import Component from 'ember-component';
import InteractivityDeferredComponent from 'web-client/mixins/interactivity-deferred-component';
import run from 'ember-runloop';
import injectService from 'ember-service/inject';

export default Component.extend(InteractivityDeferredComponent, {
  tracking: injectService(),
  playerRegistry: injectService(),
  _currentStream: null,

  didInsertElement() {
    this._super(...arguments);
    this._onContentShowing = this._onContentShowing.bind(this);
    this._createPlayer();
  },

  didReceiveAttrs() {
    let selectedStream = this.get('selectedStream');

    if (
      selectedStream &&
      selectedStream.stream &&
      selectedStream.stream.channel.name !== this._currentStream
    ) {
      this._currentStream = selectedStream.stream.channel.name;
      run.schedule('afterRender', this, this._addCampaignTracking);

      if (this.player) {
        this.player.setChannel(this._currentStream);
      }
    }

    this._super(...arguments);
  },

  _createPlayer() {
    let options = {
      branding: false,
      player: 'frontpage',
      deviceId: Twitch.idsForMixpanel.getOrCreateUniqueId(),
      channelInfo: false,
      controls: true,
      height: '100%',
      width: '100%'
    };

    if (this._currentStream) {
      options.channel = this._currentStream;
    }

    this.player = new Twitch.embed.Player('player', options);
    this.attachPlayerEventListeners();
    this.get('playerRegistry').add(this.player);
  },

  attachPlayerEventListeners() {
    this.player.addEventListener('contentShowing', this._onContentShowing);
  },
  _onContentShowing() {
    this.reportInteractive();
  },
  willDestroyElement() {
    this._currentStream = null;

    if (this.player) {
      this.player.destroy();
    }

    this._super(...arguments);
  },

  click(event) {
    let $target = this.$(event.target);

    if ($target.is('.carousel-nav a')) {
      return;
    }

    if ($target.is('.js-channel_discovery_link, .js-channel_discovery_desc a')) {
      this._trackMixpanelIndex();
    }
  },

  _trackMixpanelIndex() {
    let index = this.get('selectedStream.index');
    Twitch.storage.set('mp:source', 'front_page');
    Twitch.storage.set('mp:channel-discovery-index', index);
  },

  _addCampaignTracking() {
    Twitch.tracking.funnel.addCampaignTracking({
      selector: '.js-channel_discovery_desc a, .js-channel_discovery_link',
      'tt_medium': 'twitch_home',
      'tt_content': 'carousel'
    });
  }
});
