import _ from 'lodash';
/* eslint-disable */

function defineProperty(obj, key, value) {
  return key in obj ? Object.defineProperty(obj, value, {
    value: value,
    enumerable: !0,
    configurable: !0,
    writable: !0
  }) : obj[key] = value,
    obj
}

const isSymbol = "function" === typeof Symbol && "symbol" === typeof Symbol.iterator ? function(value) {
    return typeof value
  } : function(value) {
    return value && "function" === typeof Symbol && value.constructor === Symbol && value !== Symbol.prototype ? "symbol" : typeof value
};


function I18n() {
  this._attr = {};
  this.prepareI18n();
}

I18n.prototype.prepareI18n = function() {
  let ret = {};
  const i18ns = document.querySelectorAll("script[type=\"json/i18n\"]");
  Array.prototype.forEach.call(i18ns, i18ns => {
    try {
      ret = Object.assign({}, ret, JSON.parse(i18ns.textContent))
    } catch (e) {
      console && console.warn && console.warn("\u6587\u6848\u89E3\u6790\u5931\u8D25\uFF0C\u8282\u70B9\u5185\u5BB9\uFF1A\n%s", item.outerHTML)
    }
  })

  this.set("i18n", ret);
}

I18n.prototype.getI18n = function(key, value) {
  const name = key + (value ? "_plain": "");
  if(this.i18nMap || (this.i18nMap = {}), !this.i18nMap[name] && this.get("i18n")) {
    if(value) {
      let ret = {};
      let i18 = this.get("i18n");
      Object.keys(i18).forEach(item => {
        0 == item.indexOf(key + ".") && (ret[item.replace(key +".", "")] = i18[item])
      });
      this.i18nMap[name] = ret;
    } else {
      const obj = {
        namespace: key,
        parsePage: !1,
        locale: "zh_CN",
        langPacks: {},
        region:"CN",
        source: this.get("source") || null
      }
      obj.langPacks[obj.locale] = this.get("i18n");
      this.i18nMap[name] = new Intl(obj)
    }
  }
  return this.i18nMap[name] || null;
}

I18n.prototype.set = function(key, value) {
  _.set(this._attr, key, value);
  return _.get(this._attr, key)
}

I18n.prototype.get = function(key) {
  return _.get(this._attr, key)
}

function Intl(option) {
  this._config = option;
  this._setNamespace(option.namespace)
  this._setLocale(option.locale)
  this._setDefaultLocale(option.defaultLocale)
  this._setDefaultValue(option.defaultValue)
  this._setLangPacks(option.parsePage ? this._parsePage(): {});
  this._setLangPacks(option.langPacks);
  this._setData(option.data)
}

Intl.prototype._inspectValue = function(value) {
  return value && "string" === typeof value ? value : ""
}

Intl.prototype._parsePage = function() {
  let ret = {};
  const i18ns = document.querySelectorAll("script[type=\"json/i18n\"]");
  return Array.prototype.forEach.call(i18ns, item => {
    const locale = this._inspectValue(item.getAttribute("locale"));
    try {
      const content = JSON.parse(item.textContent);
      ret[locale] ? Object.assign(ret[locale], content): ret[locale] = content
    }catch (e) {
      console && console.warn && console.warn("\u6587\u6848\u89E3\u6790\u5931\u8D25\uFF0C\u8282\u70B9\u5185\u5BB9\uFF1A\n%s", b.outerHTML)
    }
  }), ret;
}

Intl.prototype._setNamespace = function(name) {
  this._namespace = this._inspectValue(name)
}

Intl.prototype._setLocale = function(locale) {
  this._locale = this._inspectValue(locale)
}

Intl.prototype._setDefaultLocale = function(locale) {
  this._defaultLocale = this._inspectValue(locale)
}

Intl.prototype._setDefaultValue = function(value) {
  this._defaultValue = this._inspectValue(value)
}

Intl.prototype._setLangPacks = function(pack) {
  this._langPacks || (this._langPacks = {});
  "object" !== ("undefined" === typeof pack ? "undefined" : isSymbol(pack)) && (pack = {});
  Object.keys(pack).forEach(item => {
    const data = pack[item];
    item = item || this._getLocal();
    this._langPacks[item] ? Object.assign(this._langPacks[item], data): this._langPacks[item] = data
  })
}

Intl.prototype._setData = function(data) {
  this._data || (this._data = {});
  Object.assign(this._data, data);
}

Intl.prototype._getCookieLocal = function() {
  return ("zh_CN").replace(/_/, "-").toLowerCase()
}

Intl.prototype._getBrowserLanguage = function() {
  return (navigator.language || navigator.browserLanguage || "").replace(/_/, "-").toLowerCase()
}

Intl.prototype._getLocal = function() {
  const locale = this._locale || this._defaultLocale || this._getCookieLocal() || this._getBrowserLanguage() || "zh-cn";
  return locale
}

Intl.prototype._getLangPack = function(key) {
  key= key && "undefined" !== typeof key ? key : this._getLocal();
  return this._langPacks[key]
}

Intl.prototype._getName = function(name) {
  const namespace = this._namespace;
  return "" === namespace ? name : namespace + "." + name
}

Intl.prototype._getValue = function(key, value) {
  if ("string" !== typeof key)
    return console && console.warn && console.warn("\u6587\u6848\u7D22\u5F15 [%s] \u4E0D\u5408\u7B26\u8981\u6C42\u3002", key), !1;
  const pack = this._getLangPack(value)
  const name = this._getName(key);
  return pack ? pack[name] : void 0
}

Intl.prototype._getCopy = function(a, b) {
  if ("string" === typeof a) {
    var c = "__i18n-react-split__"
      , e = {}
      , f = this
      , g = a.replace(/\{\s*(?:([^}\s]+)\s+)?([^}\s]+)(?:\s+([^}]+))*\s*\}/g, function(a, g, h, i) {
      var j;
      if (b && (j = b[h]),
      "undefined" === typeof j && (j = f._data[h] || "--"),
        g) {
        var k = Helpers[g];
        if (k)
          try {
            j = k.bind(f)(h, j, i)
          } catch (a) {
            console && console.warn && console.warn("\u8F85\u52A9\u65B9\u6CD5 [%s] \u6267\u884C\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u65B9\u6CD5\u4F53\u4EE3\u7801\u3002", g)
          }
        else
          console && console.warn && console.warn("\u8F85\u52A9\u65B9\u6CD5 [%s] \u4E0D\u5B58\u5728\uFF0C\u8BF7\u786E\u8BA4\u6587\u6848\u5B9A\u4E49\u662F\u5426\u6B63\u786E\u3002", g)
      } else
        j && "symbol" === d(j.$$typeof) && (e[h] = j,
          j = c + h + c);
      return "" + j || a
    });
    return -1 < g.indexOf(c) ? g.split(c).map(function(a, b) {
      return e[a] ? cloneElement(e[a], {
        key: b
      }) : a
    }).filter(function(a) {
      return !!a
    }) : g
  }
  return a
}

Intl.prototype.parsePage = function() {
  const parsePack = this._parsePage();
  this._setLangPacks(parsePack)
}

Intl.prototype.has = function(key, value) {
  const data = this._getValue(key, value);
  return "undefined" !== typeof data
}

Intl.prototype.get = function(obj, key, value) {
  try {
    key && "object" === ("undefined" === typeof key ? "undefined" : isSymbol(key)) && (value = key, key = this._getLocal());
    const original = this.getOriginal(obj, key);
    return original && value ? this._getCopy(original, value) : original
  } catch (c) {
    console.warn("i18n not found", obj, key, this._locale)
  }
}

Intl.prototype.getKeys = function(key) {
  let ret = []
  let namespace = "" + key
  const region = this._config.region.toUpperCase()
  const source = (this._config.source || "").toUpperCase();
  ret.push(namespace)
  namespace = namespace + "_" + region
  ret.push(namespace);
  return ret;
}

Intl.prototype.getOriginal = function(key, c) {
  c = c || this._getLocal();
  for (var d = void 0, e = void 0, data = this.getKeys(key), g = data[data.length - 1]; data.length && (e = data.pop(),
    d = this._getValue(e, c),
    !d); )
    ;
  return e && e !== g && this._setLangPacks(defineProperty({}, c, defineProperty({}, this._namespace + "." + g, d))),
  !d && console && console.warn && console.warn("[" + this._namespace + "].[" + key + "] not found in [" + c + "]"),
    d
}

Intl.prototype.getLocale = function() {
  return this._getLocal()
}

Intl.prototype.setConfig = function(config) {
  "object" !== ("undefined" === typeof config ? "undefined" : isSymbol(config)) && (config = {}),
    Object.keys(config).forEach((item) => {
      const data = "_set" + item.replace(/^(.)/, function(match) {
        return match.toUpperCase()
      });
      this[data] && this[data](config[item])
    })
}

export default new I18n();
