import React, { Component } from 'react';

import { getDisplayName } from '../../lib/components';
import Context from './Context';

/**
 * Factory to create a higher order component with injected props from site
 * @param {string} propName - Prop to inject into component
 * @returns {function} that takes the component to wrap
 */
export const siteHocFactory = (propName) => (WrappedComponent) => {
  class EnhancedComponent extends Component {
    render = () => (
      <Context.Consumer>
        { (value) => {
          if (!value || !value.site) {
            throw new Error('Cannot find <Site> to access with DataLayer');
          }

          return (
            <WrappedComponent
              { ...{ [propName]: value[propName] } }
              { ...this.props }
            />
          );
        } }
      </Context.Consumer>
    );
  }

  EnhancedComponent.displayName = getDisplayName(WrappedComponent);

  return EnhancedComponent;
};

export default siteHocFactory;
