/* globals _, Twitch, i18n */

import Component from 'ember-component';

import Ember from 'ember';
import computed from 'ember-computed';

const { inject, run } = Ember;

export default Component.extend({
  globals: inject.service(),
  broadcasterLanguages: computed.alias('globals.broadcasterLanguages'),

  tagName: 'div',
  preferredLanguage: null,
  receivedLanguage: null,
  languageCode: null,
  onChange: null,
  layoutName: 'components/broadcaster-language-picker',
  pickLanguageLabel: i18n('Pick a Language'),

  calculatedLanguageCode: computed.or('languageCode', 'preferredLanguage'),

  languageName: computed('broadcasterLanguages', 'calculatedLanguageCode', function () {
    let languageCode = this.get('calculatedLanguageCode');
    return this.get('broadcasterLanguages')[languageCode];
  }),

  languages: computed('broadcasterLanguages', 'preferredLanguage', 'calculatedLanguageCode', function () {
    // We want to have the order be: Browser Language, English, Rest Alphabetically, Other
    // Promotables are in backwards order so I can do a cool math trick.
    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) => {
      return {
        code: pair[0],
        name: pair[1],
        selected: this.get('calculatedLanguageCode') === pair[0]
      };
    });
  }),

  init: function () {
    this._super(...arguments);

    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));
    });
  },

  actions: {
    setLanguage: function () {
      let value = this.$('select').val();
      let onChange = this.get('onChange');

      if (onChange) {
        onChange(value);
      } else {
        this.set('languageCode', value);
      }
    }
  }
});
