/* globals Twitch */

import config from 'web-client/config/environment';

import Ember from 'ember';
import RSVP from 'rsvp';
import $ from 'jquery';

const { getWithDefault } = Ember;

export default {
  name: 'intl-i18n',
  initialize: function (container, application) {
    application.deferReadiness();
    let locale = getWithDefault(window, 'i18nLocale.full', config.i18n.baseLocale);

    // Intl Polyfill is needed by a small percentage (3%) of users
    let intlPolyfillPromise = new RSVP.Promise((resolve, reject) => {
      if ('Intl' in window) {
        return resolve();
      }

      $.getScript(`${config.i18n.intlPolyfillPath}/${locale}.js`).done(resolve).fail(reject);
    });
 
    // If the 'getTranslations' is not already in window, that means it wasn't part of index.html. 
    // Because Web-Client dev does not use Prod Web's index.html, the translations must be fetched lazily.
    let getTranslationsPromise = new RSVP.Promise((resolve, reject) => {
      if (config.environment !== 'development') {
        return resolve();
      }

      // Base locale translations are included in the app by default
      if (locale === config.i18n.baseLocale) {
        return resolve();
      }

      if ('getTranslations' in window && locale in window.getTranslations()) {
        return resolve();
      }

      $.getScript(`/translations/${locale}.js`).done(resolve).fail(reject);
    });

    RSVP.hashSettled({
      intlPolyfill: intlPolyfillPromise,
      getTranslations: getTranslationsPromise
    }).then((settledPromises) => {
      Object.keys(settledPromises).forEach((key) => {
        if (settledPromises[key].state === 'rejected') {
          Twitch.tracking.mixpanel.trackEvent('client_intl_i18n_errors', {errorType: key});
        }
      });
      // Because as of now the Intl libs are being used for minor features, it's better to continue loading the page
      // instead of blocking Ember from loading.
      application.advanceReadiness();
    });
  }
};
