"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.default = void 0;

var _taggedTemplateLiteralLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/taggedTemplateLiteralLoose"));

var _extends3 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _isUndefined = _interopRequireDefault(require("lodash/isUndefined"));

var _Input = _interopRequireDefault(require("../Input"));

var _FormErrorMessage = _interopRequireDefault(require("../FormErrorMessage"));

var _utils = require("../utils");

var _FormContext = _interopRequireWildcard(require("../Form/FormContext"));

var _FormGroup = require("../FormGroup/FormGroup");

function _templateObject() {
  var data = (0, _taggedTemplateLiteralLoose2.default)(["message-wrapper"]);

  _templateObject = function _templateObject() {
    return data;
  };

  return data;
}

var FormControl = /*#__PURE__*/_react.default.forwardRef(function (props, ref) {
  var _useContext = (0, _react.useContext)(_FormContext.default),
      readOnlyContext = _useContext.readOnly,
      plaintextContext = _useContext.plaintext,
      disabledContext = _useContext.disabled,
      errorFromContext = _useContext.errorFromContext,
      _useContext$formDefau = _useContext.formDefaultValue,
      formDefaultValue = _useContext$formDefau === void 0 ? {} : _useContext$formDefau,
      formError = _useContext.formError,
      onFieldChange = _useContext.onFieldChange,
      onFieldError = _useContext.onFieldError,
      onFieldSuccess = _useContext.onFieldSuccess,
      model = _useContext.model,
      contextCheckTrigger = _useContext.checkTrigger;

  var _props$as = props.as,
      Component = _props$as === void 0 ? 'div' : _props$as,
      _props$accepter = props.accepter,
      AccepterComponent = _props$accepter === void 0 ? _Input.default : _props$accepter,
      _props$classPrefix = props.classPrefix,
      classPrefix = _props$classPrefix === void 0 ? 'form-control' : _props$classPrefix,
      className = props.className,
      checkAsync = props.checkAsync,
      checkTrigger = props.checkTrigger,
      _props$errorPlacement = props.errorPlacement,
      errorPlacement = _props$errorPlacement === void 0 ? 'bottomStart' : _props$errorPlacement,
      errorMessage = props.errorMessage,
      name = props.name,
      value = props.value,
      _props$readOnly = props.readOnly,
      readOnly = _props$readOnly === void 0 ? readOnlyContext : _props$readOnly,
      _props$plaintext = props.plaintext,
      plaintext = _props$plaintext === void 0 ? plaintextContext : _props$plaintext,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? disabledContext : _props$disabled,
      onChange = props.onChange,
      onBlur = props.onBlur,
      rest = (0, _objectWithoutPropertiesLoose2.default)(props, ["as", "accepter", "classPrefix", "className", "checkAsync", "checkTrigger", "errorPlacement", "errorMessage", "name", "value", "readOnly", "plaintext", "disabled", "onChange", "onBlur"]);

  var _useContext2 = (0, _react.useContext)(_FormGroup.FormGroupContext),
      controlId = _useContext2.controlId;

  if (!onFieldChange) {
    throw new Error("\n      <FormControl> must be inside a component decorated with <Form>.\n      And need to update React to 16.6.0 +.\n    ");
  }

  var trigger = checkTrigger || contextCheckTrigger;
  var formValue = (0, _react.useContext)(_FormContext.FormValueContext);
  var val = (0, _isUndefined.default)(value) ? formValue === null || formValue === void 0 ? void 0 : formValue[name] : value;

  var _useClassNames = (0, _utils.useClassNames)(classPrefix),
      withClassPrefix = _useClassNames.withClassPrefix,
      prefix = _useClassNames.prefix,
      merge = _useClassNames.merge;

  var classes = merge(className, withClassPrefix('wrapper'));

  var handleFieldChange = function handleFieldChange(value, event) {
    handleFieldCheck(value, trigger === 'change');
    onFieldChange === null || onFieldChange === void 0 ? void 0 : onFieldChange(name, value, event);
    onChange === null || onChange === void 0 ? void 0 : onChange(value, event);
  };

  var handleFieldBlur = function handleFieldBlur(event) {
    handleFieldCheck(val, trigger === 'blur');
    onBlur === null || onBlur === void 0 ? void 0 : onBlur(event);
  };

  var handleFieldCheck = function handleFieldCheck(value, isCheckTrigger) {
    var _extends2;

    var callbackEvents = function callbackEvents(checkResult) {
      // The relevant event is triggered only when the inspection is allowed.
      if (isCheckTrigger) {
        if (checkResult.hasError) {
          onFieldError === null || onFieldError === void 0 ? void 0 : onFieldError(name, (checkResult === null || checkResult === void 0 ? void 0 : checkResult.errorMessage) || checkResult);
        } else {
          onFieldSuccess === null || onFieldSuccess === void 0 ? void 0 : onFieldSuccess(name);
        }
      }

      return checkResult;
    };

    var nextFormValue = (0, _extends3.default)({}, formValue, (_extends2 = {}, _extends2[name] = value, _extends2));

    if (checkAsync) {
      return model.checkForFieldAsync(name, nextFormValue).then(function (checkResult) {
        return callbackEvents(checkResult);
      });
    }

    return Promise.resolve(callbackEvents(model.checkForField(name, nextFormValue)));
  };

  var messageNode = null;

  if (!(0, _isUndefined.default)(errorMessage)) {
    messageNode = errorMessage;
  } else if (errorFromContext) {
    var fieldError = formError === null || formError === void 0 ? void 0 : formError[name];

    if (typeof fieldError === 'string' || !(fieldError === null || fieldError === void 0 ? void 0 : fieldError.array) && !(fieldError === null || fieldError === void 0 ? void 0 : fieldError.object) && (fieldError === null || fieldError === void 0 ? void 0 : fieldError.hasError)) {
      messageNode = fieldError;
    }
  }

  var ariaDescribedby = controlId ? controlId + "-" + (messageNode ? 'error-message' : 'help-text') : null;
  return /*#__PURE__*/_react.default.createElement(Component, {
    className: classes,
    ref: ref
  }, /*#__PURE__*/_react.default.createElement(AccepterComponent, (0, _extends3.default)({
    id: controlId,
    "aria-labelledby": controlId ? controlId + "-control-label" : null,
    "aria-describedby": ariaDescribedby
  }, rest, {
    readOnly: readOnly,
    plaintext: plaintext,
    disabled: disabled,
    name: name,
    onChange: handleFieldChange,
    onBlur: handleFieldBlur,
    defaultValue: formDefaultValue[name],
    value: val
  })), /*#__PURE__*/_react.default.createElement(_FormErrorMessage.default, {
    id: controlId + "-error-message",
    role: "alert",
    "aria-relevant": "all",
    show: !!messageNode,
    className: prefix(_templateObject()),
    placement: errorPlacement
  }, messageNode));
});

FormControl.displayName = 'FormControl';
FormControl.propTypes = {
  name: _propTypes.default.string.isRequired,
  checkTrigger: _propTypes.default.oneOf(['change', 'blur', 'none']),
  checkAsync: _propTypes.default.bool,
  accepter: _propTypes.default.any,
  onChange: _propTypes.default.func,
  onBlur: _propTypes.default.func,
  classPrefix: _propTypes.default.string,
  errorMessage: _propTypes.default.node,
  errorPlacement: _propTypes.default.oneOf(['bottomStart', 'bottomEnd', 'topStart', 'topEnd', 'leftStart', 'rightStart', 'leftEnd', 'rightEnd']),
  value: _propTypes.default.any
};
var _default = FormControl;
exports.default = _default;