import extend from 'extend';
import React from 'react';

import enhancer, { enhancerMultiple } from './ItemEnhancerContainer';
import { resetKdModel } from './kdModelHelper';

function resetWrapper(Item) {

  const EnhancedItem = Item.name === 'KdSelectEntityMultiple' ? enhancerMultiple(Item) : enhancer(Item);

  return class ItemEnhancerContainer extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        component: () =>
          <EnhancedItem
            ref={ref => (this.Component = ref)}
            {...this.props}
          />,
      };
    }

    reset = () => {
      resetKdModel({ items: this.getChicklets() });
      if (this.Component) {
        this.Component.state.stateValue.itemsState = [];
        this.Component.state.stateValue.errorState = null;
      }
      this.setState({
        component: () =>
          <EnhancedItem
            ref={ref => (this.Component = ref)}
            {...this.props}
          />,
      });
    }

    hardReset = () => {
      const { selectedValuesInitial } = this.props;
      const propsWithOutInitial = extend(true, {}, this.props);
      if (selectedValuesInitial && selectedValuesInitial.length) {
        delete propsWithOutInitial.selectedValuesInitial;
      }
      this.setState({
        component: () =>
          <EnhancedItem
            ref={ref => (this.Component = ref)}
            {...propsWithOutInitial}
          />,
      });
    }

    executeValidation = () => {
      return this.Component && !this.Component.state.stateValue.errorState;
    }

    getValidation = () => {
      return this.Component && this.Component.state.stateValue.errorState;
    }

    getChicklets = () => {
      return this.Component && this.Component.state.stateValue.itemsState;
    }

    clearAll = () => {
      resetKdFilter({ items: this.getChicklets() });
      this.hardReset();
    }

    render() {
      const Component = this.state.component;
      return (
        <div>
          <Component />
        </div>
      );
    }
  };
}

export default resetWrapper;
