"use strict";

function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.t = exports.setStore = exports.mergeTranslations = exports.getLocale = exports["default"] = exports.changeLocale = exports.T = exports.L = exports.Hyphenated = void 0;
exports.translateComponent = translateComponent;
exports.translations = exports.translationExists = void 0;
exports.use = use;
exports.useTranslationWithoutStore = useTranslationWithoutStore;
var _reactReduxI18n = require("react-redux-i18n");
var _react = _interopRequireWildcard(require("react"));
var _server = _interopRequireDefault(require("react-dom/server"));
var _reactRedux = require("react-redux");
var _get = _interopRequireDefault(require("lodash/get"));
var _isObject = _interopRequireDefault(require("lodash/isObject"));
var _isString = _interopRequireDefault(require("lodash/isString"));
var _merge = _interopRequireDefault(require("lodash/merge"));
var _reactHyphen = _interopRequireDefault(require("react-hyphen"));
var _configuration = require("../App/configuration");
var _excluded = ["escapeDot"],
  _excluded2 = ["escapeDot"];
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = _getPrototypeOf(t); if (r) { var s = _getPrototypeOf(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return _possibleConstructorReturn(this, e); }; }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
/**
 * The Redux Store object
 * @type Store
 */
var store;

/**
 * The setup method
 *  - sets the store object used for redux
 *  - sets the locale
 *  - adds the pre-init translations map
 * @param {Store} reduxStore
 */
var setStore = exports.setStore = function setStore(reduxStore, initialCode) {
  if (!reduxStore.getState || !reduxStore.dispatch) {
    throw new Error('A valid redux store must be given!');
  }
  store = reduxStore;
  if (store && initialCode) {
    // set the locale from the configuration
    changeLocale(initialCode);
  }

  // Adds the pre-init translations
  mergeTranslations(translations);
};

/**
 * Global translations object (pre-setup)
 * @type {{}}
 */
var translations = exports.translations = {};

/**
 * Function to handle the missing translations.
 * It simply replaces the '[DOT]' with '.' in the key and returns that
 * It is needed because the i18n module uses the dot symbol as a property accessor
 * @param {string} key
 * @param replacements
 */
// eslint-disable-next-line no-unused-vars
var HandleMissingTranslation = function HandleMissingTranslation(key, replacements) {
  return key.replace(/\[DOT\]/g, '.');
};
_reactReduxI18n.I18n.setHandleMissingTranslation(HandleMissingTranslation);

/**
 * Function to merge the local (module related) translations into the global dictionary
 *  - call it with a translation object eg. { en: { greeting: 'Hi!' }, de: { greeting: 'Hallo!' } }
 *  - useful to call it from within a Translation.js file, doing it this way one need only to import it
 * @param {Object} translationsObject
 */
var mergeTranslations = exports.mergeTranslations = function mergeTranslations(translationsObject) {
  if (!store) {
    throw new Error('Store must be set up first!');
  }
  var translations = (0, _merge["default"])(store.getState().i18n.translations || {}, translationsObject);
  store.dispatch((0, _reactReduxI18n.loadTranslations)(translations));
};

/**
 * Function to change the locale
 * @param {string} locale
 */
var changeLocale = exports.changeLocale = function changeLocale(locale) {
  if (!store) {
    throw new Error('Store must be set up first!');
  }
  store.dispatch((0, _reactReduxI18n.setLocale)(locale.replace('_', '-')));
};

/**
 * Function to return the current locale
 * @return {string} The current locale
 */
var getLocale = exports.getLocale = function getLocale() {
  if (!store) {
    throw new Error('Store must be set up first!');
  }
  return store.getState().i18n.locale;
};

/**
 * Translates the given text
 * @param {string} value - The text to translate
 * @param {Object} props - The props passed to the Translate Component. Can contain (escapeDot: true)
 * to search with '[DOT]' instead of '.' (which is used as a property accessor)
 * @return {*}
 * @constructor
 */
var T = exports.T = function T(value) {
  var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  // eslint-disable-next-line react/prop-types
  var escapeDot = props.escapeDot,
    otherProps = _objectWithoutProperties(props, _excluded);
  if (value === undefined) {
    return value;
  } else if (escapeDot && (0, _isString["default"])(value)) {
    value = value.replace(/\./g, '[DOT]');
  }
  if ((0, _isObject["default"])(otherProps)) {
    for (var p in otherProps) {
      // if the replacement is a jsx element, just render it in place
      if ( /*#__PURE__*/_react["default"].isValidElement(otherProps[p])) {
        otherProps[p] = _server["default"].renderToStaticMarkup(otherProps[p]);
      }
    }
  }
  return /*#__PURE__*/_react["default"].createElement(_reactReduxI18n.Translate, _extends({
    value: '' + value,
    dangerousHTML: true
  }, otherProps));
};

/**
 * Localize the given value
 * @param {*} value - The value to localize
 * @param {Object} props - The props passed to the Localize Component. Can contain (escapeDot: true)
 * to search with '[DOT]' instead of '.' (which is used as a property accessor)
 * @return {*}
 * @constructor
 */
var L = exports.L = function L(value) {
  var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  // eslint-disable-next-line react/prop-types
  var escapeDot = props.escapeDot,
    otherProps = _objectWithoutProperties(props, _excluded2);
  if (value === undefined) {
    return value;
  } else if (escapeDot && (0, _isString["default"])(value)) {
    value = value.replace(/\./g, '[DOT]');
  }
  return /*#__PURE__*/_react["default"].createElement(_reactReduxI18n.Localize, _extends({
    value: '' + value
  }, otherProps));
};
var Hyphenated = exports.Hyphenated = (0, _reactRedux.connect)(function (_ref) {
  var locale = _ref.i18n.locale;
  return {
    locale: locale
  };
})(function (_ref2) {
  var children = _ref2.children,
    locale = _ref2.locale;
  var hyphenations = (0, _configuration.getConf)('hyphenations');
  if (hyphenations[locale]) {
    return locale === 'en-GB' ? /*#__PURE__*/_react["default"].createElement(_reactHyphen["default"], null, children) : /*#__PURE__*/_react["default"].createElement(_reactHyphen["default"], {
      language: hyphenations[locale]
    }, children);
  }
  return children;
});

/**
 * Function to merge the local (module related) translations into the global dictionary
 *  - call it with a translation object eg. { en: { greeting: 'Hi!' }, de: { greeting: 'Hallo!' } }
 *  - useful to call it from within a Translation.js file, doing it this way one need only to import it
 * @param {Object} translationsObject
 */
function use(translationsObject) {
  if (store && store.dispatch) {
    // if store exists just call the merge function
    mergeTranslations(translationsObject);
  } else {
    // merge with pre-init translations
    (0, _merge["default"])(translations, translationsObject);
  }
}

/**
 * Checks if translation exists for the given key
 * @param {string} key - The key of the translation
 * @return {boolean}
 * @constructor
 */
var translationExists = exports.translationExists = function translationExists(key) {
  // Copied from react-i18nify, I18n._translate
  var locale = _reactReduxI18n.I18n._translations[_reactReduxI18n.I18n._locale] ? _reactReduxI18n.I18n._locale : _reactReduxI18n.I18n._locale.split('-')[0];
  var translations = _reactReduxI18n.I18n._translations[locale];
  if (!translations) {
    return false;
  }
  var translation = (0, _get["default"])(translations, key, null);
  return translation !== null;
};
var _default = exports["default"] = {
  use: use,
  changeLocale: changeLocale,
  getLocale: getLocale,
  T: T,
  L: L
};
function translateComponent(ComponentToTranslate, mapStateToProps, mapDispatchToProps) {
  var TranslatedComponent = /*#__PURE__*/function (_Component) {
    _inherits(TranslatedComponent, _Component);
    var _super = _createSuper(TranslatedComponent);
    function TranslatedComponent(props) {
      var _this;
      _classCallCheck(this, TranslatedComponent);
      _this = _super.call(this, props);
      // decorate the component, so it can use directly the t() function
      _defineProperty(_assertThisInitialized(_this), "setRef", function (ref) {
        _this.wrappedInstance = ref;
      });
      ComponentToTranslate.prototype.t = _this.t;
      return _this;
    }
    _createClass(TranslatedComponent, [{
      key: "t",
      value: function t() {
        if (store) {
          return _reactReduxI18n.I18n.t.apply(_reactReduxI18n.I18n, arguments);
        } else {
          throw new Error('Store must be set up first!');
        }
      }
    }, {
      key: "render",
      value: function render() {
        // if not child of Component return without ref
        if (!ComponentToTranslate.prototype.render) {
          return /*#__PURE__*/_react["default"].createElement(ComponentToTranslate, _objectSpread(_objectSpread({}, this.props), {}, {
            t: this.t
          }));
        }
        return /*#__PURE__*/_react["default"].createElement(ComponentToTranslate, _extends({
          ref: this.setRef
        }, _objectSpread(_objectSpread({}, this.props), {}, {
          t: this.t
        })));
      }
    }]);
    return TranslatedComponent;
  }(_react.Component); // mapping state.locale to the locale prop, so the component will update when locale changes
  function mapMergedProps(state) {
    return _objectSpread(_objectSpread({}, mapStateToProps instanceof Function && mapStateToProps(state)), {}, {
      locale: state.i18n.locale
    });
  }
  return (0, _reactRedux.connect)(mapMergedProps, mapDispatchToProps)(TranslatedComponent);
}
var t = exports.t = _reactReduxI18n.I18n.t.bind(_reactReduxI18n.I18n);
function useTranslationWithoutStore() {
  _reactReduxI18n.I18n.setTranslationsGetter(function () {
    return translations;
  });
  _reactReduxI18n.I18n.setLocaleGetter(function () {
    return 'en-GB';
  });
}
// eslint-disable-next-line react-hooks/rules-of-hooks
useTranslationWithoutStore();
window.changeLocale = changeLocale;