import React from 'react';
import PropTypes from 'prop-types';
import { withNaming as SetupBem } from '@bem-react/classname';

// http://bem.github.io/bem-react/interfaces/ipreset.html
const BEM = SetupBem({
  e: '-',
  m: '_',
  v: '=',
});

export default BEM;

/**
 * A core React component class which your elements can extend to add support for generating standard BEM classes on the fly. See [`@bem-react/classname`](https://github.com/bem/bem-react/tree/master/packages/classname#bem-reactclassname---) for further information on how we generate BEM classes.
 */
export const Component = class BEMComponent extends React.Component {
  static propTypes = {
    bem: PropTypes.oneOfType([PropTypes.string, PropTypes.array, PropTypes.object]),
  };

  static defaultProps = {
    bem: '',
  };

  constructor(props, rootClass) {
    super(props);

    const bemRoot = rootClass || `${this.constructor}`.match(/function\s?(\S*)\s?\(/)[1];
    const bemClass = BEM(bemRoot);

    this.bem = (E, M, X) => bemClass(E, M, X);

    this.bem.modifiersFromArray = arg =>
      (Array.isArray(arg) &&
        arg.reduce((sum, key) => {
          sum[key] = true;
          return sum;
        }, {})) ||
      arg;

    this.bem.classes = () => {
      const bem = Array.isArray(this.props.bem) ? this.props.bem : [this.props.bem];
      const cls = [this.props.className || ''];
      return this.bem(...bem.map(this.bem.modifiersFromArray), cls);
    };
  }
};
