import _extends from "@babel/runtime/helpers/esm/extends";
import _get from "lodash/get";
import * as React from 'react';
import { setDisplayName, wrapDisplayName } from 'recompose';
import defaultLocale from './locales/default';
import IntlContext from './IntlContext';
import extendReactStatics from '../utils/extendReactStatics';

var mergeObject = function mergeObject(list) {
  return list.reduce(function (a, b) {
    a = _extends({}, a, {}, b);
    return a;
  }, {});
};

function withLocale(combineKeys) {
  if (combineKeys === void 0) {
    combineKeys = [];
  }

  return function (BaseComponent) {
    var WithLocale = React.forwardRef(function (props, ref) {
      return React.createElement(IntlContext.Consumer, null, function (value) {
        var locale = mergeObject(combineKeys.map(function (key) {
          return _get(value || defaultLocale, "" + key);
        }));

        if (value && typeof value.rtl !== undefined) {
          locale.rtl = value.rtl;
        } else if (typeof window !== 'undefined' && (document.body.getAttribute('dir') || document.dir) === 'rtl') {
          locale.rtl = true;
        }

        return React.createElement(BaseComponent, _extends({
          ref: ref,
          locale: locale
        }, props));
      });
    });
    WithLocale.displayName = BaseComponent.displayName;
    extendReactStatics(WithLocale, BaseComponent);

    if (process.env.RUN_ENV === 'test') {
      return setDisplayName(wrapDisplayName(BaseComponent, '__test__'))(WithLocale);
    }

    return setDisplayName(wrapDisplayName(BaseComponent, 'withLocale'))(WithLocale);
  };
}

export default withLocale;