"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.setStringsLoader = setStringsLoader;
exports.setStrings = setStrings;
exports.loadStrings = loadStrings;
exports.getStrings = getStrings;
exports.createStringsLoader = createStringsLoader;

var _merge = _interopRequireDefault(require("lodash/merge"));

var _cloneDeep = _interopRequireDefault(require("lodash/cloneDeep"));

var config = _interopRequireWildcard(require("./config"));

var strings;
var loader;

function setStringsLoader(l) {
  loader = l;
}

function setStrings(strs) {
  strings = strs;
}

function loadStrings(loc) {
  //TODO Catch locale load error and load default
  return new Promise(function (resolve, reject) {
    if (!loader) {
      throw new Error('Strings loader have not been configured yet, check startup sequence');
    } //if (!config.getConfig().userLanguage) throw new Error('Locale has not been configured');


    if (undefined !== loc) {
      config.getConfig().userLanguage = loc;
    }

    resolve(loader(config.getConfig().userLanguage));
  }).then(function (strs) {
    setStrings(strs);
    return strs;
  });
}
/**
 * @return LANG_STRINGS
 */


function getStrings() {
  if (!strings) {
    throw new Error('Strings have not been loaded yet, check startup sequence');
  }

  return strings;
}

function createStringsLoader(loader, en_US, localize) {
  var defaultStrings = (0, _cloneDeep.default)(en_US);
  return function (locale) {
    return loader(locale).then(function (newStrings) {
      // loader returns null if locale is default
      if (!newStrings) {
        newStrings = defaultStrings;
      }

      (0, _merge.default)(en_US, defaultStrings, newStrings); // Now localization strings are available and UI library can be localized

      if (localize && 'COMMON' in en_US) {
        localize(en_US.COMMON);
      }

      setStrings(en_US);
      return en_US;
    });
  };
}