import _regeneratorRuntime from "@babel/runtime/regenerator";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _createForOfIteratorHelper from "@babel/runtime/helpers/createForOfIteratorHelper";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
var _excluded = ["__useDynamicElements_original_props__"],
    _excluded2 = ["customizer", "children"];
import { mapValues, omitBy } from 'lodash';
import { forwardRef, useEffect, useState } from 'react';
import { defineMessage } from 'react-intl';
import { defineMessages } from '@formatjs/intl';
import { jsx as _jsx } from "react/jsx-runtime";
export var setDefaultType = function setDefaultType(type) {
  return function (config) {
    return _objectSpread({
      type: type
    }, config);
  };
};
export var typesWithElements = ['form', 'formGroup'];
export var omitDeepBy = function omitDeepBy(object, test) {
  return mapValues(omitBy(object, test), function traverse(entry) {
    return Array.isArray(entry) ? entry.map(traverse) : typeof entry === 'object' ? omitDeepBy(entry, test) : entry;
  });
};
export var ensureValueIsAvailable = function ensureValueIsAvailable(value, list) {
  return list.find(function (item) {
    return item.value === value;
  }) ? value : undefined;
};
export function useStatePreferInitial(initialState) {
  var state = useState(initialState);
  useEffect(function () {
    var _state = _slicedToArray(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;
}
export var withPropsUpdater = function withPropsUpdater(updater) {
  return function (Component) {
    return /*#__PURE__*/forwardRef(function (_ref, ref) {
      var __useDynamicElements_original_props__ = _ref.__useDynamicElements_original_props__,
          props = _objectWithoutProperties(_ref, _excluded);

      return __useDynamicElements_original_props__ ? /*#__PURE__*/_jsx(Component, _objectSpread(_objectSpread({
        ref: ref
      }, updater(_objectSpread(_objectSpread({}, props), {}, {
        __useDynamicElements_original_props__: __useDynamicElements_original_props__
      }))), {}, {
        __useDynamicElements_original_props__: updater(__useDynamicElements_original_props__)
      })) : /*#__PURE__*/_jsx(Component, _objectSpread({
        ref: ref
      }, updater(props)));
    });
  };
};
export 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 : _objectSpread(_objectSpread({}, 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.

export var chain = function chain(funcs) {
  return /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var _len,
        args,
        _key,
        _iterator,
        _step,
        func,
        proceed,
        _args = arguments;

    return _regeneratorRuntime.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 = _createForOfIteratorHelper(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, _toConsumableArray(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]]);
  }));
};
export function Customize(_ref3) {
  var Customizer = _ref3.customizer,
      children = _ref3.children,
      otherProps = _objectWithoutProperties(_ref3, _excluded2);

  return Customizer ? /*#__PURE__*/_jsx(Customizer, _objectSpread(_objectSpread({}, otherProps), {}, {
    children: children
  })) : children;
}
export 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;
}
var generalErrorMessages = defineMessages({
  duplicateKeyError: {
    id: "+I4cMz",
    defaultMessage: [{
      "type": 0,
      "value": "Vaihtoehdoissa ei saa olla duplikaatti vierasavaimia."
    }]
  }
});
export var generalValidators = {
  noDuplicateKeys: {
    name: defineMessage({
      id: "DUByOW",
      defaultMessage: [{
        "type": 0,
        "value": "Ei duplikaatti avaimia"
      }]
    }),
    fn: function fn(value, _) {
      if (value && value.length > 0) {
        var keys = [];

        var _iterator2 = _createForOfIteratorHelper(value),
            _step2;

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

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