import React from "react";
import _ from "lodash";

/* eslint import/no-anonymous-default-export: [2, {"allowArrowFunction": true}] */
export default (triggerMs = 0) => {
  return ReactElement => {
    class DebounceInput extends React.Component {
      constructor(props) {
        super(props);
        this.state = {};
        this.state.value = props.value;
      }

      componentDidUpdate(preProps, preState) {
        if (preProps.value !== this.props.value) {
          this.setState({ value: this.props.value });
        }
      }

      onChange = (() => {
        let updb = this.props.onChange;
        if (triggerMs >= 0) {
          updb = _.debounce(value => {
            this.props.onChange(value);
          }, triggerMs);
        }
        return updb;
      })();

      handleOnChange = event => {
        const {
          target: { value }
        } = event;
        this.setState({ value });
        return this.onChange(value);
      };

      render() {
        const theProps = {
          ...this.props,
          ...this.state
        };
        theProps.onChange = this.handleOnChange;
        return <ReactElement {...theProps} />;
      }
    }

    return DebounceInput;
  };
};
