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

const DEFAULT_LANGUAGE = 'en';

export default Service.extend({
  geo: injectService(),
  storage: injectService(),

  getRecommendationLanguages() {
    let geo = this.get('geo');
    let storage = this.get('storage');
    return geo.getGeo().then((info) => {
      if (this.isDestroyed) { return; }
      let receivedLanguage = info.received_language || '';
      receivedLanguage = receivedLanguage.slice(0, 2);
      let languageFiltersJSON = storage.get('languageDirectoryFilters');
      let languageFilters;
      try {
        languageFilters = JSON.parse(languageFiltersJSON);
      } catch(e) {
        languageFilters = [];
      }
      let languages = [];
      if (receivedLanguage !== '') {
        languages = [ receivedLanguage ];
      } else if (languageFilters.length > 0) {
        languages = languageFilters;
      } else {
        languages = [ DEFAULT_LANGUAGE ];
      }
      return languages;
    });
  }
});
