"use strict";

require("core-js/modules/es.symbol");

require("core-js/modules/es.symbol.description");

require("core-js/modules/es.symbol.iterator");

require("core-js/modules/es.array.concat");

require("core-js/modules/es.array.filter");

require("core-js/modules/es.array.for-each");

require("core-js/modules/es.array.is-array");

require("core-js/modules/es.array.iterator");

require("core-js/modules/es.array.join");

require("core-js/modules/es.array.map");

require("core-js/modules/es.object.create");

require("core-js/modules/es.object.define-properties");

require("core-js/modules/es.object.define-property");

require("core-js/modules/es.object.get-own-property-descriptor");

require("core-js/modules/es.object.get-own-property-descriptors");

require("core-js/modules/es.object.get-prototype-of");

require("core-js/modules/es.object.keys");

require("core-js/modules/es.object.set-prototype-of");

require("core-js/modules/es.object.to-string");

require("core-js/modules/es.reflect.get");

require("core-js/modules/es.string.iterator");

require("core-js/modules/web.dom-collections.for-each");

require("core-js/modules/web.dom-collections.iterator");

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

var _react = _interopRequireDefault(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _ValueSubscriber2 = _interopRequireDefault(require("../ValueSubscriber"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }

function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

var runValidationRules = function runValidationRules(rules, value, invalidate) {
  if (_typeof(rules) === 'object') {
    if (Array.isArray(rules)) {
      rules.forEach(function (rule) {
        return runValidationRules(rule, value, invalidate);
      });
    } else {
      Object.keys(rules).forEach(function (key) {
        runValidationRules(rules[key], value[key], function (error) {
          var nestedName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
          return invalidate(error, [key].concat(nestedName));
        });
      });
    }
  } else {
    rules(value, invalidate);
  }
};

exports.runValidationRules = runValidationRules;

var Validation =
/*#__PURE__*/
function (_ValueSubscriber) {
  _inherits(Validation, _ValueSubscriber);

  function Validation(props, context) {
    var _this;

    _classCallCheck(this, Validation);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(Validation).call(this, props, context));
    _this.state = _objectSpread({}, _this.state, {
      validationResult: []
    }); // setState may fire asynchronously, so we need to track the state with a property for rapid updates.

    _this.dirtyValidationResult = [];
    return _this;
  }

  _createClass(Validation, [{
    key: "triggerUpdate",
    value: function triggerUpdate() {
      _get(_getPrototypeOf(Validation.prototype), "triggerUpdate", this).call(this);

      this.runValidation();
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      _get(_getPrototypeOf(Validation.prototype), "componentDidMount", this).call(this);

      this.runValidation();
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      _get(_getPrototypeOf(Validation.prototype), "componentWillUnmount", this).call(this);

      this.context.ffUpdateValidation(this.state.validationResult, []);
    } // TODO: If the rules prop changes, revalidate

  }, {
    key: "runValidation",
    value: function runValidation() {
      var value = this.getValue();
      var result = [];

      var invalidate = function invalidate(error) {
        var nestedName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
        result.push([nestedName, error]);
      };

      runValidationRules(this.props.rules, value, invalidate); // Check validation results for differences

      if (this.dirtyValidationResult.length === result.length) {
        var validationChanged = false;
        var i = 0;

        while (validationChanged === false && i < result.length) {
          var newVal = result[i];
          var oldVal = this.dirtyValidationResult[i];

          if (newVal[0].join('|') !== oldVal[0].join('|') || newVal[1] !== oldVal[1]) {
            validationChanged = true;
          }

          i += 1;
        }

        if (validationChanged === false) {
          return;
        }
      }

      var oldResult = this.dirtyValidationResult; // Track the new validation outside of the state, to prevent async race conditions

      this.dirtyValidationResult = result;
      this.setState({
        validationResult: result
      });
      this.context.ffUpdateValidation(oldResult, result);
    }
    /**
     * Override this to change how the validation errors are rendered
     * @public
     */

  }, {
    key: "renderErrors",
    value: function renderErrors() {
      if (this.state.validationResult.length === 0) {
        return null;
      }

      return _react["default"].createElement("ul", null, this.state.validationResult.map(function (v, i) {
        return _react["default"].createElement("li", {
          key: i
        }, v[1]);
      }));
    }
  }, {
    key: "render",
    value: function render() {
      var displayBeforeChildren = this.props.displayBeforeChildren;

      var children = _get(_getPrototypeOf(Validation.prototype), "render", this).call(this);

      return _react["default"].createElement(_react["default"].Fragment, null, displayBeforeChildren ? null : children, this.renderErrors(), displayBeforeChildren ? children : null);
    }
  }]);

  return Validation;
}(_ValueSubscriber2["default"]);

exports["default"] = Validation;

_defineProperty(Validation, "propTypes", _objectSpread({}, _ValueSubscriber2["default"].propTypes, {
  /**
   * Validation rules can be specified as a single function, an array of functions,
   * an object of functions, or an object of arrays of functions. Functions will
   * receive the form values at this level, and objects will return the matching
   * value for its key.
   * @param {any} value The value to be validated
   * @param {function} invalidate A function that may be called with an error string
   */
  rules: _propTypes["default"].oneOfType([_propTypes["default"].func, _propTypes["default"].arrayOf(_propTypes["default"].func), _propTypes["default"].objectOf([_propTypes["default"].func, _propTypes["default"].arrayOf(_propTypes["default"].func)])]).isRequired,

  /**
   * Should error messages be displayed before or after the children
   */
  displayBeforeChildren: _propTypes["default"].bool
}));

_defineProperty(Validation, "defaultProps", _objectSpread({}, _ValueSubscriber2["default"].defaultProps, {
  displayBeforeChildren: false
}));

_defineProperty(Validation, "contextTypes", _objectSpread({}, _ValueSubscriber2["default"].contextTypes, {
  ffUpdateValidation: _propTypes["default"].func.isRequired
}));