"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getValidationState = getValidationState;
exports.getValidation = getValidation;
exports.validate = void 0;

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

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

var _throttle = require("@audentio/utils/lib/throttle");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function getValidationState(validationErrors) {
  var errors = {};
  validationErrors.inner.forEach(function (field) {
    errors[field.path] = field.errors;
  });
  return errors;
}
/**
 * Validate form using objectschema generated by `renderFields`
 */


function getValidation(value) {
  var fields = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  return new Promise(function (resolve) {
    // quit early if there's nothing to validate
    if (Object.keys(fields).length === 0) {
      resolve({
        isValid: true,
        errors: null
      });
      return;
    }

    Promise.resolve().then(function () {
      return _interopRequireWildcard(require('yup'));
    }).then(function (yup) {
      return yup.object().shape(fields);
    }).then(function (formSchema) {
      formSchema.validate(value, {
        abortEarly: false
      }).then(function () {
        var result = {
          isValid: true,
          errors: null
        };
        resolve(result);
      })["catch"](function (validationErrors) {
        var result = {
          isValid: false,
          errors: getValidationState(validationErrors)
        };
        resolve(result);
      });
    });
  });
}
/**
 * validate form and update state
 * throttled so it can be called on fast-triggering events
 */


var validate = (0, _throttle.throttle)( /*#__PURE__*/function () {
  var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(value, fields, onValidate) {
    var _yield$getValidation, isValid, errors;

    return _regenerator["default"].wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            _context.next = 2;
            return getValidation(value, fields);

          case 2:
            _yield$getValidation = _context.sent;
            isValid = _yield$getValidation.isValid;
            errors = _yield$getValidation.errors;
            onValidate({
              isValid: isValid,
              errors: errors
            });

          case 6:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));

  return function (_x, _x2, _x3) {
    return _ref.apply(this, arguments);
  };
}(), 500);
exports.validate = validate;
//# sourceMappingURL=formValidation.js.map