import React from 'react';
import PropTypes from 'prop-types';
import { FormattedNumber } from 'react-intl';

const IntlConfig = PropTypes.shape({
  localeCode: PropTypes.string,
  defaultCurrency: PropTypes.string,
});

export class IntlConfigProvider extends React.Component {
  static childContextTypes = {
    intlConfig: IntlConfig,
  };

  getChildContext() {
    const { config } = this.props;
    return { intlConfig: config };
  }

  render() {
    const { children } = this.props;
    return children;
  }
}

IntlConfigProvider.propTypes = {
  config: IntlConfig,
  children: PropTypes.node,
};

IntlConfigProvider.defaultProps = {
  config: {
    localeCode: 'en-gb',
    defaultCurrency: 'GBP'
  },
  children: '',
};

export const injectIntlConfig = (Component) => {
  const ExportedComponent = (props, context) => {
    const { intlConfig } = context;
    return (
      <Component {...props} intlConfig={intlConfig} />
    );
  };

  ExportedComponent.contextTypes = {
    intlConfig: IntlConfig,
  };

  return ExportedComponent;
};

export const FormattedCurrency = injectIntlConfig((props) => {
  const { intlConfig } = props;

  return (/* eslint-disable-next-line react/style-prop-object */
    <FormattedNumber style="currency" currency={intlConfig.defaultCurrency} {...props} />
  );
});
