var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

import React from 'react';
import Instance from './instance';

function Context(_ref) {
  var _ref$locale = _ref.locale,
      locale = _ref$locale === undefined ? {} : _ref$locale,
      language = _ref.language,
      portal = _ref.portal,
      children = _ref.children;

  var data = null;
  // 根据语言名称获取locale数据
  function initLanguageLocale() {
    var seedsuiLocale = {};
    var result = require('./../locale/' + language + '.js');
    if (!result) {
      console.error('seedsui\u4E2D, ' + language + '\u8BED\u8A00\u5305\u4E0D\u5B58\u5728');
      data = locale;
      return;
    }
    // 防止没有用babel-plugin-add-module-exports自动加上default
    if (result.default) seedsuiLocale = result.default;
    data = _extends({}, seedsuiLocale, locale);
  }
  // 有language属性时, 读取seedsui内部国际化文件
  if (language) {
    initLanguageLocale();
  } else {
    data = locale;
  }
  if (!data || Object.keys(data).length === 0) {
    console.log('读取默认国际化文件zh_CN');
    data = require('./../locale/zh_CN.js');
  }
  if (data && Object.keys(data).length) localStorage.setItem('_seedsui_locale', JSON.stringify(data));
  return React.createElement(
    Instance.Provider,
    {
      value: {
        locale: function locale(remark, key, variable) {
          if (!data) return key || '';
          // 获取key的值
          if (key) {
            var value = data[key] || '';
            if (value && variable && Array.isArray(variable) && variable.length) {
              for (var i = 0; i < variable.length; i++) {
                if (typeof variable[i] !== 'number' && typeof variable[i] !== 'boolean' && typeof variable[i] !== 'string') continue;
                value = value.replace(new RegExp('\\{' + i + '\\}', 'g'), variable[i]);
              }
            }
            return value || remark || key;
          }
          // 如果有remark, 没有key, 则返回remark
          if (remark) {
            return remark;
          }
          return data;
        },
        language: language,
        portal: portal
      }
    },
    children
  );
}

export default Context;