/* globals SiteOptions, Twitch, i18n, _ */

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'),
  languageDirectoryFilter: injectService(),

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

  renderTemplate: function () {
    this._super(this, arguments);
    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);

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

  model() {
    return new RSVP.Promise(function (resolve) {
      Twitch.geo.then(function () {
        resolve(StreamModel.find('top').load());
      });
    }, 'ChannelsAllRoute#model');
  },

  afterModel() {
    this.set('languageDirectoryFilter.gameName', '');
    this._super(...arguments);
  },

  buildPageTitle() {
    return {title: i18n('Top Channels')};
  },

  trackPageView(properties) {
    if (this.get('usePageViewPromise')) {
      this.get('tracking.funnel').trackPageViewWithDiagnostics(
        RSVP.hash({
          'num_language_channels': this.controllerFor('directory/channels/all').get('languageChannelsCountPromise')
        }).then(function (results) {
          return this._getPageViewProperties(properties, results);
        }.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')
    });
  }
});
