"use strict";

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

exports.__esModule = true;
exports["default"] = void 0;

var _react = _interopRequireDefault(require("react"));

var _browserLang = _interopRequireDefault(require("browser-lang"));

var _gatsby = require("gatsby");

var _reactIntl = require("react-intl");

var _intlContext = require("./intl-context");

var preferDefault = function preferDefault(m) {
  return m && m["default"] || m;
};

var getLocaleData = function getLocaleData(locale) {
  try {
    var localeData = require("react-intl/locale-data/" + locale);

    return localeData;
  } catch (e) {
    return false;
  }
};

var addLocaleDataForGatsby = function addLocaleDataForGatsby(language) {
  var localeData = null;
  localeData = getLocaleData(language);

  if (!localeData && language.length > 2) {
    var locale = language.substring(0, 2);
    localeData = getLocaleData(locale);
  }

  if (!localeData) {
    throw new Error("Cannot find react-intl/locale-data/" + language);
  }

  _reactIntl.addLocaleData.apply(void 0, localeData);
};

var _default = function _default(_ref) {
  var element = _ref.element,
      props = _ref.props;

  if (!props) {
    return;
  }

  var intl = props.pageContext.intl;
  var language = intl.language,
      languages = intl.languages,
      messages = intl.messages,
      redirect = intl.redirect,
      routed = intl.routed;
  /* eslint-disable no-undef */

  var isRedirect = redirect && !routed;

  if (isRedirect) {
    var pathname = props.location.pathname; // Skip build, Browsers only

    if (typeof window !== "undefined") {
      var saved = window.localStorage.getItem("gatsby-intl-language");

      if (!languages.includes(saved)) {
        saved = language;
      }

      var detected = saved || (0, _browserLang["default"])({
        languages: languages,
        fallback: language
      });
      var newUrl = (0, _gatsby.withPrefix)("/" + detected + pathname);
      window.localStorage.setItem("gatsby-intl-language", detected);
      window.location.replace(newUrl);
    }
  }

  if (typeof window !== "undefined") {
    window.___gatsbyIntl = intl;
  }

  addLocaleDataForGatsby(language);
  return _react["default"].createElement(_reactIntl.IntlProvider, {
    locale: language,
    messages: messages
  }, _react["default"].createElement(_intlContext.IntlContextProvider, {
    value: intl
  }, isRedirect ? GATSBY_INTL_REDIRECT_COMPONENT_PATH && _react["default"].createElement(preferDefault(require(GATSBY_INTL_REDIRECT_COMPONENT_PATH))) : element));
};

exports["default"] = _default;