import Service from 'ember-service';
import injectService from 'ember-service/inject';

export default Service.extend({
  receivedLanguage: '',
  isLoaded: false,

  api: injectService(),
  geo: injectService(),

  init() {
    this._super(...arguments);
    this._cachedRequests = {};
    this._strings = {};
    this._loadStrings();
  },

  getString(key, defaultString) {
    let strings = this._strings;
    let lang = this.get('receivedLanguage');

    if (!lang || !strings[lang] || !strings[lang][key]) {
      return defaultString || '';
    }
    return strings[lang][key];
  },

  _requestBitsStrings(lang) {
    let cachedRequests = this._cachedRequests;
    if (cachedRequests.hasOwnProperty(lang)) {
      return cachedRequests[lang];
    }

    let requestBitsPromise = this.get('api').request('get', `/bits/strings?locale=${lang}`)
      .catch(() => {
        this._cachedRequests[lang] = null;
      });

    this._cachedRequests[lang] = requestBitsPromise;
    return requestBitsPromise;
  },

  _loadStrings() {
    this.get('geo').getGeo().then(response => {
      if (this.isDestroyed) {
        return;
      }

      let lang = response['received_language'];
      this.set('receivedLanguage', lang);

      this._requestBitsStrings(lang)
        .then((obj) => {
          if (this.isDestroyed) {
            return;
          }

          this._strings[lang] = this._transformStringResponse(obj.strings);
          this.set('isLoaded', true);
        });
    });
  },

  _transformStringResponse(strings) {
    let stringMap = {};
    strings.forEach((string) => {
      stringMap[string.key] = string.value;
    });

    return stringMap;
  }
});
