"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createStatefulPropHoc = createStatefulPropHoc;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const getDisplayName = Comp => Comp.displayName || Comp.name || 'UnnamedComponent';
function createStatefulPropHoc(fieldname, updater = 'updateValue') {
  return Comp => {
    class WrappedControlledInput extends _react.default.PureComponent {
      constructor(props) {
        super(props);
        (0, _defineProperty2.default)(this, "handleChange", ev => {
          if (ev.target) {
            this.setState({
              value: ev.target.value
            });
          } else {
            this.setState({
              value: ev
            });
          }
        });
        this.state = {
          value: props[fieldname]
        };
      }
      UNSAFE_componentWillReceiveProps(nextProps) {
        this.setState({
          value: nextProps[fieldname]
        });
      }
      render() {
        const passedProps = {
          ...this.props,
          [fieldname]: this.state.value,
          [updater]: this.handleChange
        };
        return /*#__PURE__*/_react.default.createElement(Comp, passedProps);
      }
    }
    WrappedControlledInput.propTypes = {
      [fieldname]: _propTypes.default.any
    };

    // set the display name of the wrapped component, for easier debugging
    WrappedControlledInput.displayName = `statefulProp(${getDisplayName(Comp)})`;
    return WrappedControlledInput;
  };
}