import _taggedTemplateLiteralLoose from "@babel/runtime/helpers/esm/taggedTemplateLiteralLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";

function _templateObject() {
  var data = _taggedTemplateLiteralLoose(["message-wrapper"]);

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

  return data;
}

import React, { useContext } from 'react';
import PropTypes from 'prop-types';
import isUndefined from 'lodash/isUndefined';
import Input from '../Input';
import FormErrorMessage from '../FormErrorMessage';
import { useClassNames } from '../utils';
import FormContext, { FormValueContext } from '../Form/FormContext';
import { FormGroupContext } from '../FormGroup/FormGroup';
/**
 * Props that FormControl passes to its accepter
 */

var FormControl = /*#__PURE__*/React.forwardRef(function (props, ref) {
  var _useContext = useContext(FormContext),
      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 : _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 = _objectWithoutPropertiesLoose(props, ["as", "accepter", "classPrefix", "className", "checkAsync", "checkTrigger", "errorPlacement", "errorMessage", "name", "value", "readOnly", "plaintext", "disabled", "onChange", "onBlur"]);

  var _useContext2 = useContext(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 = useContext(FormValueContext);
  var val = isUndefined(value) ? formValue === null || formValue === void 0 ? void 0 : formValue[name] : value;

  var _useClassNames = 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 = _extends({}, 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 (!isUndefined(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.createElement(Component, {
    className: classes,
    ref: ref
  }, /*#__PURE__*/React.createElement(AccepterComponent, _extends({
    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.createElement(FormErrorMessage, {
    id: controlId + "-error-message",
    role: "alert",
    "aria-relevant": "all",
    show: !!messageNode,
    className: prefix(_templateObject()),
    placement: errorPlacement
  }, messageNode));
});
FormControl.displayName = 'FormControl';
FormControl.propTypes = {
  name: PropTypes.string.isRequired,
  checkTrigger: PropTypes.oneOf(['change', 'blur', 'none']),
  checkAsync: PropTypes.bool,
  accepter: PropTypes.any,
  onChange: PropTypes.func,
  onBlur: PropTypes.func,
  classPrefix: PropTypes.string,
  errorMessage: PropTypes.node,
  errorPlacement: PropTypes.oneOf(['bottomStart', 'bottomEnd', 'topStart', 'topEnd', 'leftStart', 'rightStart', 'leftEnd', 'rightEnd']),
  value: PropTypes.any
};
export default FormControl;