/* globals Twitch, _, SiteOptions */

import Route from 'ember-route';
import StreamModel from 'web-client/models/deprecated-stream';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import RSVP from 'rsvp';
import { isFollowingColumnInteractive } from 'web-client/utilities/interactivity';

export default Route.extend({
  globals: injectService(),
  layout: injectService(),
  tracking: injectService(),
  excludedLocalizedContentLanguages: computed.alias('globals.excludedLocalizedContentLanguages'),
  community: injectService(),

  renderTemplate() {
    this._super();
    this.set('usePageViewPromise', false);

    if (Twitch.receivedLanguage) {
      let twoLetterLanguageCode = Twitch.receivedLanguage.slice(0, 2);
      let excludedLocalizedContentLanguages = this.get('excludedLocalizedContentLanguages');
      if (!_.contains(excludedLocalizedContentLanguages, twoLetterLanguageCode) &&
          _.contains(_.keys(SiteOptions.broadcaster_languages), twoLetterLanguageCode)) {
        this.set('usePageViewPromise', true);
        let game = this.modelFor('directory.game').get('id');
        let findBy = this.get('community').isCreativeManagedGame(game) ? "gameWithCommunity" : "bygame";

        this.render("directory/game/channels/broadcaster-language-sample", {
          outlet: 'localizedContent',
          into: 'directory/game/index',
          controller: 'directory/game/broadcaster-language',
          model: StreamModel.find(findBy, {
            game,
            broadcaster_language: twoLetterLanguageCode
          }).load()
        });
      }
    }
  },

  model() {
    let self = this;

    let game = this.modelFor('directory.game').get('id');
    let findBy = this.get('community').isCreativeManagedGame(game) ? "gameWithCommunity" : "bygame";

    return new RSVP.Promise(function (resolve) {
      Twitch.geo.then(function () {
        resolve(StreamModel.find(findBy, {game: self.modelFor('directory.game').get('id')}).load());
      });
    }, 'GameDirectoryIndexRoute#model');
  },

  isInteractive(interactiveComponents) {
    return isFollowingColumnInteractive(interactiveComponents) &&
      (interactiveComponents['stream-preview'] || interactiveComponents['beacon:no-directory-channels-are-live']);
  },

  /**
   * This pageview does not always have a loading dependency, since the loading dependency depends
   *   on the user's inclusion in the experiment set up above in #renderTemplate.
   * @param properties
   */
  trackPageView(properties) {
    if (this.get('usePageViewPromise')) {
      this.get('tracking.funnel').trackPageViewWithDiagnostics(
        RSVP.hash({
          'num_language_channels': this.controllerFor('directory.game').get('languageChannelsCountPromise')
        }).then(function (params) {
          return this._getPageViewProperties(properties, params);
        }.bind(this))
      );
    } else {
      this.get('tracking.funnel').trackPageView(this._getPageViewProperties(properties));
    }
  },

  _getPageViewProperties(properties, additionalParams) {
    additionalParams = additionalParams || {};

    return _.defaults(properties, additionalParams, {
      'collapse_language': this.get('layout.hideLocalizedContentSection'),
      'game': this.controllerFor('directory.game').get('content.id')
    });
  }
});
