import React from 'react';
import lGet from 'lodash.get';
import Context from '../FreactalStateContext';
import StoreContext from '../FreactalStoreContext';

const defaultReducer = (props, state = {}, actions = {}) => ({
  ...props,
  state,
  actions,
});

export default (View, reducer) => class WrappedComponent extends React.PureComponent {
  static contextType = Context;

  combineProps(store) {
    const actions = lGet(store, 'combinedActions', {});
    return (reducer || defaultReducer)(
      this.props,
      lGet(this, 'context', {}),
      actions,
      store,
    );
  }

  render() {
    return (
      <StoreContext.Consumer>
        {(store) => {
          const props = this.combineProps(store);
          return (<View {...props} />);
        }}
      </StoreContext.Consumer>
    );
  }
};
