import React from 'react';
import _ from 'lodash';

import { addLocaleData, IntlProvider } from 'react-intl';

import messagesBase from './locales/messages.json';

export default function setIntl(messagesDataExt, WrappedComponent, localeData) {
  const messagesData = _.merge(_.cloneDeep(messagesBase), messagesDataExt || {});

  addLocaleData(localeData);

  let language = (navigator.languages && navigator.languages[0])
    || navigator.language
    || navigator.userLanguage;

  let language6391 = language.toLowerCase().split(/[_-]+/)[0];

  if (!(language6391 in messagesData)) {
    language = 'en';
    language6391 = 'en';
  }

  const messages = messagesData[language6391] || messagesData[language] || messagesData.en;

  return props => (
    <IntlProvider
      locale={language}
      messages={messages}
    >
      <WrappedComponent {...props} />
    </IntlProvider>
  );
}
