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

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

function resetWrapper(Item) {
  let EnhancedItem;

  if (Item.name === 'KdSelectEntityMultiple') {
    EnhancedItem = enhancerMultiple(Item);
  } else if (Item.name === 'KdSelectSortOrder') {
    EnhancedItem = enhancerSortable(Item);
  } else {
    EnhancedItem = enhancer(Item);
  }

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

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

    reset = () => {
      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;
