import _extends from "@babel/runtime/helpers/esm/extends";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
import React from 'react';
import { getDisplayName } from "../getDisplayName";
var removePostfix = function removePostfix(word, postfixRegex) {
  var regexContent = postfixRegex.source.replace(/\$$/, '');
  var isCorrectPostfix = postfixRegex.test(word);
  if (!isCorrectPostfix) {
    throw new Error("Component's displayName property must end with '" + regexContent + "' in order to be wrapped in withClassWrapper HOC");
  }
  return word.replace(postfixRegex, '');
};

/**
 * HOC for moving from Class to Functional components.
 *
 * Used to remove distinctions between Class and Functional refs.
 *
 * @param RFC Functional component wrapped in forwardRefAndName.
 * @returns Class component that wraps Functional component.
 */
export function withClassWrapper(RFC) {
  var _ClassWrapper;
  var fullName = getDisplayName(RFC);
  var nameWithoutPostfix = removePostfix(fullName, /FC$/);
  return _ClassWrapper = /*#__PURE__*/function (_React$Component) {
    function ClassWrapper() {
      var _this;
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
      _this.instancePropertiesRef = /*#__PURE__*/React.createRef();
      return _this;
    }
    _inheritsLoose(ClassWrapper, _React$Component);
    var _proto = ClassWrapper.prototype;
    _proto.componentDidMount = function componentDidMount() {
      if (this.instancePropertiesRef.current) {
        Object.defineProperties(this, Object.getOwnPropertyDescriptors(this.instancePropertiesRef.current));
      }
    };
    _proto.render = function render() {
      return /*#__PURE__*/(
        // @ts-expect-error: TypeScript is not able to understand that both types (class one and functional one) have ref.
        React.createElement(ClassWrapper.FC, _extends({
          // Returns methods defined in useImperativeHandle.
          instanceRef: this.instancePropertiesRef
        }, this.props))
      );
    };
    return ClassWrapper;
  }(React.Component), _ClassWrapper.__KONTUR_REACT_UI__ = nameWithoutPostfix, _ClassWrapper.displayName = nameWithoutPostfix, _ClassWrapper.FC = RFC, _ClassWrapper;
}