/*
 * This file is generated by parrot must
 * DOCUMENT LIST:
 * parrot must: http://gitlab.alibaba-inc.com/parrot/parrot-tool-must
 * @ali/global-locale: http://gitlab.alibaba-inc.com/parrot/global-locale
 * @ali/global-string-format: http://gitlab.alibaba-inc.com/parrot/global-string-format
 */

import locale from '@ali/global-locale';
import stringFormat from '@ali/global-string-format';
import strings from './strings';

let language; // Current language
let intl; // Instance of intl-universal. Create by provideIntl
/**
 * update instance of intl universal
 */
function update() {
  const { lang } = locale.getLocale();
  language = lang;
  intl = stringFormat.init(lang, strings);
}

/**
 * change current language
 * @param {string} langTag language tag config above
 */
function change(langTag) {
  locale.setLang(langTag);
  update();
}
/**
 * Format string by key
 * For example:
 * $i18n.get('jsx.home.title'),
 * $i18n.get({
 *    id: 'jsx.home.hello',
 *    defaultMessage: 'Hello {name}' // not required
 * },{
 *  name: 'Alice'
 * })
 * More syntax: https://formatjs.io/guides/message-syntax/
 * @param {string|object} id key or object
 * @param {object} variable variable for id
 * @return {string} format message
 */
function get(id, variable) {
  if (!intl) update();
  if (typeof id === 'string') {
    return stringFormat.format(
      {
        id: id,
      },
      variable,
    );
  } else if (typeof id === 'object' && id.dm) {
    id.defaultMessage = id.dm;
  }
  return stringFormat.format(
    {
      id: id.id,
      defaultString: id.dm,
    },
    variable,
  );
}

/* set the first hng cookie
 * //! IMPORTANT  remove this after published, only for demo to start up
 * //! IMPORTANT 项目第一次启动后请删除下边的逻辑，这个逻辑只是为了第一次运行的时候，项目能够切换到英文
 */
// Delete start
change('en-US');
// Delete end

module.exports = {
  get,
  update,
  change,
  language,
};
