"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = withCustomValidation;

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

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

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

var _react = require("react");

var _text = require("./configToSchemas/types/text");

var _tableField = require("./configToSchemas/types/tableField");

var _formGroupList = require("./configToSchemas/typePlugins/formGroupList");

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

var _reactIntl = require("react-intl");

var _jsxRuntime = require("react/jsx-runtime");

var _excluded = ["config", "validate"];

var elementHasValidator = function elementHasValidator(element) {
  return element.validator && element.validator !== 'none';
};

function withCustomValidation(Form) {
  return /*#__PURE__*/(0, _react.forwardRef)(function (_ref, ref) {
    var config = _ref.config,
        _validate2 = _ref.validate,
        props = (0, _objectWithoutProperties2["default"])(_ref, _excluded);
    var intl = (0, _reactIntl.useIntl)();
    var formType = config.type;
    var validateElements = (formType === 'form' || formType === 'formGroup' ? config.elements : [config]).map(function (element) {
      if (element.type === 'formGroup') {
        return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, element), {}, {
          elements: element.elements.filter(elementHasValidator)
        });
      } else {
        return element;
      }
    }).filter(function (element) {
      var _element$elements;

      return element.type === 'formGroup' && ((_element$elements = element.elements) === null || _element$elements === void 0 ? void 0 : _element$elements.length) > 0 || elementHasValidator(element);
    });

    if (validateElements.length > 0) {
      var validateFunctions = {
        text: _text.validators,
        tableField: _tableField.validators,
        formGroup: _formGroupList.validators
      };

      var validateOne = function validateOne(formData, errors, element, listIndex) {
        var _validateFunctions$ty, _functions$validator, _functions$validator$;

        var key = element.key,
            type = element.type,
            validator = element.validator,
            useLabel = element.useLabel,
            label = element.label,
            labelError = element.labelError,
            title = element.title;
        var functions = (_validateFunctions$ty = validateFunctions[type]) !== null && _validateFunctions$ty !== void 0 ? _validateFunctions$ty : _utils.generalValidators;
        var errorMessage = functions === null || functions === void 0 ? void 0 : (_functions$validator = functions[validator]) === null || _functions$validator === void 0 ? void 0 : (_functions$validator$ = _functions$validator.fn) === null || _functions$validator$ === void 0 ? void 0 : _functions$validator$.call(_functions$validator, formData, element);

        if (errorMessage) {
          var elementTitle = useLabel ? label === "" ? labelError : label : title;
          var formattedErrorMessage = intl.formatMessage(errorMessage, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, element), {}, {
            title: elementTitle
          }));

          if (key) {
            if (listIndex !== undefined) {
              var _errors$key, _errors$key$listIndex;

              errors === null || errors === void 0 ? void 0 : (_errors$key = errors[key]) === null || _errors$key === void 0 ? void 0 : (_errors$key$listIndex = _errors$key[listIndex]) === null || _errors$key$listIndex === void 0 ? void 0 : _errors$key$listIndex.addError(formattedErrorMessage);
            } else {
              var _errors$key2;

              errors === null || errors === void 0 ? void 0 : (_errors$key2 = errors[key]) === null || _errors$key2 === void 0 ? void 0 : _errors$key2.addError(formattedErrorMessage);
            }
          } else {
            if (listIndex !== null && listIndex !== undefined) {
              var _errors$listIndex;

              errors === null || errors === void 0 ? void 0 : (_errors$listIndex = errors[listIndex]) === null || _errors$listIndex === void 0 ? void 0 : _errors$listIndex.addError(formattedErrorMessage);
            } else {
              errors === null || errors === void 0 ? void 0 : errors.addError(formattedErrorMessage);
            }
          }
        }
      };

      var validateFormGroup = function validateFormGroup(formData, errors, elements, listIndex) {
        if (listIndex !== undefined) {
          var _iterator = (0, _createForOfIteratorHelper2["default"])(elements),
              _step;

          try {
            for (_iterator.s(); !(_step = _iterator.n()).done;) {
              var element = _step.value;
              var key = element.key,
                  list = element.list;

              if (list) {
                for (var dataIndex in formData[key]) {
                  validateOne(formData[listIndex][dataIndex], errors[listIndex], element, dataIndex);
                }
              } else {
                validateOne(formData[key], errors[listIndex], element);
              }
            }
          } catch (err) {
            _iterator.e(err);
          } finally {
            _iterator.f();
          }
        } else {
          var _iterator2 = (0, _createForOfIteratorHelper2["default"])(elements),
              _step2;

          try {
            for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
              var _element = _step2.value;
              var _key = _element.key,
                  _list = _element.list;

              if (_list) {
                for (var _dataIndex in formData[_key]) {
                  validateOne(formData[_key][_dataIndex], errors, _element, _dataIndex);
                }
              } else if (formData) {
                validateOne(formData[_key], errors, _element);
              }
            }
          } catch (err) {
            _iterator2.e(err);
          } finally {
            _iterator2.f();
          }
        }
      };

      var validateForm = function validateForm(formData, errors, elements) {
        var _iterator3 = (0, _createForOfIteratorHelper2["default"])(elements),
            _step3;

        try {
          for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
            var element = _step3.value;
            var key = element.key,
                type = element.type,
                list = element.list,
                validator = element.validator;

            if (list) {
              if (type === 'formGroup') {
                if (validator) {
                  validateOne(formData[key], errors, element);
                } else {
                  for (var dataIndex in formData[key]) {
                    validateFormGroup(formData[key][dataIndex], errors[key], element.elements, dataIndex);
                  }
                }
              } else {
                for (var _dataIndex2 in formData[key]) {
                  validateOne(formData[key][_dataIndex2], errors, element, _dataIndex2);
                }
              }
            } else if (type === 'formGroup') {
              validateFormGroup(formData[key], errors[key], element.elements);
            } else {
              validateOne(formData[key], errors, element);
            }
          }
        } catch (err) {
          _iterator3.e(err);
        } finally {
          _iterator3.f();
        }

        return errors;
      };

      var validateAll = function validateAll(formData, errors, elements) {
        switch (formType) {
          case 'form':
            return validateForm(formData, errors, elements);

          case 'formGroup':
            return config.list ? validateForm({
              0: formData
            }, {
              0: errors
            }, [(0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, config), {}, {
              key: 0,
              elements: elements
            })]) : validateForm(formData, errors, elements);

          default:
            return validateForm({
              0: formData
            }, errors, [(0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, elements[0]), {}, {
              key: 0
            })]);
        }
      };

      return /*#__PURE__*/(0, _jsxRuntime.jsx)(Form, (0, _objectSpread2["default"])({
        config: config,
        validate: function validate(formData, errors) {
          var _validate;

          errors = validateAll(formData, errors, validateElements);
          return (_validate = _validate2 === null || _validate2 === void 0 ? void 0 : _validate2(formData, errors)) !== null && _validate !== void 0 ? _validate : errors;
        },
        ref: ref
      }, props));
    } else {
      return /*#__PURE__*/(0, _jsxRuntime.jsx)(Form, (0, _objectSpread2["default"])({
        config: config,
        validate: _validate2,
        ref: ref
      }, props));
    }
  });
}
//# sourceMappingURL=withCustomValidation.cjs.map