"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useStatePreferInitial = useStatePreferInitial;
exports.Customize = Customize;
exports.getAriaLabel = getAriaLabel;
exports.generalValidators = exports.ariaDescribedBy = exports.errorsId = exports.helpId = exports.descriptionId = exports.chain = exports.sortChoices = exports.withPropsUpdater = exports.ensureValueIsAvailable = exports.omitDeepBy = exports.typesWithElements = exports.setDefaultType = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

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

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

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

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

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

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

var _lodash = require("lodash");

var _react = require("react");

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

var _intl = require("@formatjs/intl");

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

var _excluded = ["__useDynamicElements_original_props__"],
    _excluded2 = ["customizer", "children"];

var setDefaultType = function setDefaultType(type) {
  return function (config) {
    return (0, _objectSpread2["default"])({
      type: type
    }, config);
  };
};

exports.setDefaultType = setDefaultType;
var typesWithElements = ['form', 'formGroup'];
exports.typesWithElements = typesWithElements;

var omitDeepBy = function omitDeepBy(object, test) {
  return (0, _lodash.mapValues)((0, _lodash.omitBy)(object, test), function traverse(entry) {
    return Array.isArray(entry) ? entry.map(traverse) : typeof entry === 'object' ? omitDeepBy(entry, test) : entry;
  });
};

exports.omitDeepBy = omitDeepBy;

var ensureValueIsAvailable = function ensureValueIsAvailable(value, list) {
  return list.find(function (item) {
    return item.value === value;
  }) ? value : undefined;
};

exports.ensureValueIsAvailable = ensureValueIsAvailable;

function useStatePreferInitial(initialState) {
  var state = (0, _react.useState)(initialState);
  (0, _react.useEffect)(function () {
    var _state = (0, _slicedToArray2["default"])(state, 2),
        value = _state[0],
        setValue = _state[1];

    if (value !== initialState) {
      setValue(initialState);
    } // We intentionally	run this effect only on when initialState changes
    // eslint-disable-next-line react-hooks/exhaustive-deps

  }, [initialState]);
  return state;
}

var withPropsUpdater = function withPropsUpdater(updater) {
  return function (Component) {
    return /*#__PURE__*/(0, _react.forwardRef)(function (_ref, ref) {
      var __useDynamicElements_original_props__ = _ref.__useDynamicElements_original_props__,
          props = (0, _objectWithoutProperties2["default"])(_ref, _excluded);
      return __useDynamicElements_original_props__ ? /*#__PURE__*/(0, _jsxRuntime.jsx)(Component, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({
        ref: ref
      }, updater((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, props), {}, {
        __useDynamicElements_original_props__: __useDynamicElements_original_props__
      }))), {}, {
        __useDynamicElements_original_props__: updater(__useDynamicElements_original_props__)
      })) : /*#__PURE__*/(0, _jsxRuntime.jsx)(Component, (0, _objectSpread2["default"])({
        ref: ref
      }, updater(props)));
    });
  };
};

exports.withPropsUpdater = withPropsUpdater;

var sortChoices = function sortChoices() {
  var choices = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var autoSort = arguments.length > 1 ? arguments[1] : undefined;
  var choicesSorted = choices.map(function (choice, index) {
    return choice["enum"] ? choice : (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, choice), {}, {
      "enum": "".concat(index)
    });
  });

  if (autoSort) {
    choicesSorted.sort(function (el1, el2) {
      var el1Name = el1.enumNames ? el1.enumNames : el1["enum"];
      var el2Name = el2.enumNames ? el2.enumNames : el2["enum"];

      if (el1Name > el2Name) {
        return 1;
      } else if (el1Name < el2Name) {
        return -1;
      }

      return 0;
    });
  }

  return choicesSorted;
}; // Chain function calls until some returns falsy return value. Optionally update args.


exports.sortChoices = sortChoices;

var chain = function chain(funcs) {
  return /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() {
    var _len,
        args,
        _key,
        _iterator,
        _step,
        func,
        proceed,
        _args = arguments;

    return _regenerator["default"].wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            for (_len = _args.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
              args[_key] = _args[_key];
            }

            _iterator = (0, _createForOfIteratorHelper2["default"])(funcs.filter(Boolean));
            _context.prev = 2;

            _iterator.s();

          case 4:
            if ((_step = _iterator.n()).done) {
              _context.next = 14;
              break;
            }

            func = _step.value;
            _context.next = 8;
            return func.apply(void 0, (0, _toConsumableArray2["default"])(args));

          case 8:
            proceed = _context.sent;

            if (Array.isArray(proceed)) {
              args = proceed;
            }

            if (proceed) {
              _context.next = 12;
              break;
            }

            return _context.abrupt("return", proceed);

          case 12:
            _context.next = 4;
            break;

          case 14:
            _context.next = 19;
            break;

          case 16:
            _context.prev = 16;
            _context.t0 = _context["catch"](2);

            _iterator.e(_context.t0);

          case 19:
            _context.prev = 19;

            _iterator.f();

            return _context.finish(19);

          case 22:
            return _context.abrupt("return", args);

          case 23:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[2, 16, 19, 22]]);
  }));
};

exports.chain = chain;

function Customize(_ref3) {
  var Customizer = _ref3.customizer,
      children = _ref3.children,
      otherProps = (0, _objectWithoutProperties2["default"])(_ref3, _excluded2);
  return Customizer ? /*#__PURE__*/(0, _jsxRuntime.jsx)(Customizer, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, otherProps), {}, {
    children: children
  })) : children;
}

function getAriaLabel(label, options, required, requiredMessage) {
  var ariaLabel = label;

  if (!ariaLabel) {
    var element = options.element;
    ariaLabel = element.useLabel ? element.label === "" || !element.label ? element.labelError : element.label : element.title;
  }

  if (required) {
    ariaLabel = "".concat(requiredMessage, ": ").concat(ariaLabel);
  }

  return ariaLabel;
} // Create a consistent id for the field description element


var descriptionId = function descriptionId(id) {
  return "".concat(id, "__description");
}; // Create a consistent id for the field help element


exports.descriptionId = descriptionId;

var helpId = function helpId(id) {
  return "".concat(id, "__help");
}; // Create a consistent id for the field errors element


exports.helpId = helpId;

var errorsId = function errorsId(id) {
  return "".concat(id, "__errors");
}; // Create a list of element ids that contain additional information about the
// field


exports.errorsId = errorsId;

var ariaDescribedBy = function ariaDescribedBy(id, uiSchema, rawErrors) {
  var _uiSchema$uiOptions, _uiSchema$uiOptions$e, _uiSchema$element, _uiSchema$uiOptions2, _uiSchema$uiOptions2$, _uiSchema$element2, _uiSchema$uiOptions3, _uiSchema$uiOptions3$;

  var listElement = uiSchema === null || uiSchema === void 0 ? void 0 : (_uiSchema$uiOptions = uiSchema["ui:options"]) === null || _uiSchema$uiOptions === void 0 ? void 0 : (_uiSchema$uiOptions$e = _uiSchema$uiOptions.element) === null || _uiSchema$uiOptions$e === void 0 ? void 0 : _uiSchema$uiOptions$e.list;
  var ariaId = "".concat(uiSchema["ui:description"] || (uiSchema === null || uiSchema === void 0 ? void 0 : (_uiSchema$element = uiSchema.element) === null || _uiSchema$element === void 0 ? void 0 : _uiSchema$element.description) || ((_uiSchema$uiOptions2 = uiSchema["ui:options"]) === null || _uiSchema$uiOptions2 === void 0 ? void 0 : (_uiSchema$uiOptions2$ = _uiSchema$uiOptions2.element) === null || _uiSchema$uiOptions2$ === void 0 ? void 0 : _uiSchema$uiOptions2$.description) ? descriptionId(listElement ? id.substring(0, id.lastIndexOf("_")) : id) : "", " ").concat(uiSchema["ui:help"] || (uiSchema === null || uiSchema === void 0 ? void 0 : (_uiSchema$element2 = uiSchema.element) === null || _uiSchema$element2 === void 0 ? void 0 : _uiSchema$element2.help) || ((_uiSchema$uiOptions3 = uiSchema["ui:options"]) === null || _uiSchema$uiOptions3 === void 0 ? void 0 : (_uiSchema$uiOptions3$ = _uiSchema$uiOptions3.element) === null || _uiSchema$uiOptions3$ === void 0 ? void 0 : _uiSchema$uiOptions3$.help) ? helpId(listElement ? id.substring(0, id.lastIndexOf("_")) : id) : "", " ").concat((rawErrors === null || rawErrors === void 0 ? void 0 : rawErrors.length) > 0 ? errorsId(id) : "");

  if (ariaId !== "" && ariaId.length > 2) {
    return ariaId;
  }
};

exports.ariaDescribedBy = ariaDescribedBy;
var generalErrorMessages = (0, _intl.defineMessages)({
  duplicateKeyError: {
    id: "+I4cMz",
    defaultMessage: [{
      "type": 0,
      "value": "Vaihtoehdoissa ei saa olla duplikaatti vierasavaimia."
    }]
  },
  missingKeyError: {
    id: "6NoS+a",
    defaultMessage: [{
      "type": 0,
      "value": "Vaihtoehdoilla täytyy olla vierasavaimet."
    }]
  }
});
var generalValidators = {
  noDuplicateKeys: {
    name: (0, _reactIntl.defineMessage)({
      id: "DUByOW",
      defaultMessage: [{
        "type": 0,
        "value": "Ei duplikaatti avaimia"
      }]
    }),
    fn: function fn(value, _) {
      if (value && value.length > 0) {
        var keys = [];

        var _iterator2 = (0, _createForOfIteratorHelper2["default"])(value),
            _step2;

        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
            var choice = _step2.value;

            if (!choice["enum"]) {
              return generalErrorMessages.missingKeyError;
            } else if (!keys.includes(choice["enum"])) {
              keys.push(choice["enum"]);
            } else {
              return generalErrorMessages.duplicateKeyError;
            }
          }
        } catch (err) {
          _iterator2.e(err);
        } finally {
          _iterator2.f();
        }
      }
    }
  }
};
exports.generalValidators = generalValidators;
//# sourceMappingURL=utils.cjs.map