/* globals Twitch, _, i18n */

import Service from 'ember-service';

import computed from 'ember-computed';
import StreamModel from 'web-client/models/deprecated-stream';
import injectService from 'ember-service/inject';
import run from 'ember-runloop';

export default Service.extend({
  globals: injectService(),
  broadcasterLanguages: computed.alias('globals.broadcasterLanguages'),
  experiments: injectService(),
  languageFilters: [],
  gameName: '',
  preferredLanguage: null,
  receivedLanguage: null,
  calculatedLanguageCode: computed.or('languageCode', 'preferredLanguage'),
  community: injectService(),

  languages: computed('broadcasterLanguages', 'preferredLanguage', 'calculatedLanguageCode', function () {
    // copied from broadcaster-language-picker
    let preferredLanguage = this.get('preferredLanguage') || '';
    let receivedLanguage = this.get('receivedLanguage') || '';
    let backwardsPromotables = ['en', receivedLanguage, preferredLanguage];
    let demotables = ['asl', 'other'];
    let broadcasterLanguages = this.get('broadcasterLanguages');
    let languages = _.sortBy(_.pairs(broadcasterLanguages), function (pair) {
      if (_.contains(demotables, pair[0])) {
        return (demotables.indexOf(pair[0]) + backwardsPromotables.length + 1) + pair[1];
      }
      return (backwardsPromotables.indexOf(pair[0]) * -1) + pair[1];
    });

    return _.map(languages, (pair) => {
      if (pair[1] === 'Other') {
        pair[1] = i18n(pair[1]);
      }
      return {
        code: pair[0],
        name: pair[1],
        selected: this.get('calculatedLanguageCode') === pair[0]
      };
    });
  }),

  streams: computed('languageFilters', 'gameName', function () {
    let languageFilters = this.get('languageFilters');
    let game = this.get('gameName');
    let findBy = this.get('community').isCreativeManagedGame(game) ? "gameWithCommunity" : "bygame";

    return StreamModel.find(findBy, {
      game,
      broadcaster_language: languageFilters.join(',')
    }).load();
  }),

  init() {
    this._super();
    Twitch.geo.then((info) => {
      let preferredLanguage = info.preferred_language || '';
      let receivedLanguage = info.received_language || '';
      run(this, this.set, 'preferredLanguage', preferredLanguage.slice(0, 2));
      run(this, this.set, 'receivedLanguage', receivedLanguage.slice(0, 2));
    });
    let languageFilters = Twitch.storage.getObject('languageDirectoryFilters');
    this.set('languageFilters', languageFilters || []);
  },

  setLanguageFilters(languages) {
    this.set('languageFilters', languages);
    Twitch.storage.setObject('languageDirectoryFilters', languages);
  }

});
