"use strict";

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

var _util = require("./util");

var _validator = require("./validator");

var _messages2 = _interopRequireDefault(require("./messages"));

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

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

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 _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 _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 noop() {}

var Schema =
/*#__PURE__*/
function () {
  function Schema(rules) {
    var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

    _classCallCheck(this, Schema);

    this._rules = rules;
    this._options = _objectSpread({}, options, {
      messages: _objectSpread({}, _messages2["default"], {}, options.messages)
    });
    this.complete = [];
  }

  _createClass(Schema, [{
    key: "abort",
    value: function abort() {
      for (var i = 0; i < this.complete.length; i++) {
        this.complete[i] = noop;
      }
    }
  }, {
    key: "messages",
    value: function messages(_messages) {
      this._options.messages = _extends({}, this._options.messages, _messages);
    }
  }, {
    key: "validate",
    value: function validate(source, callback) {
      var _this = this;

      if (!this._rules || Object.keys(this._rules).length === 0) {
        if (callback) {
          callback(null);
        }

        return;
      } // serialize rules


      var arr;
      var value;
      var series = {};
      var names = Object.keys(this._rules);
      names.forEach(function (name) {
        arr = _this._rules[name];
        value = source[name];

        if (!Array.isArray(arr)) {
          arr = [arr];
        }

        arr.forEach(function (rule) {
          rule.validator = (0, _validator.getValidationMethod)(rule);
          rule.field = name;

          if (!rule.validator) {
            return;
          }

          series[name] = series[name] || [];
          series[name].push({
            rule: rule,
            value: value,
            source: source,
            field: name
          });
        });
      });

      if (Object.keys(series).length === 0) {
        callback(null);
      } // callback function for all rules return


      function complete(results) {
        var i;
        var field;
        var errors = [];
        var fields = {};

        function add(e) {
          if (Array.isArray(e)) {
            errors = errors.concat(e);
          } else {
            errors.push(e);
          }
        }

        for (i = 0; i < results.length; i++) {
          add(results[i]);
        }

        if (!errors.length) {
          errors = null;
          fields = null;
        } else {
          for (i = 0; i < errors.length; i++) {
            field = errors[i].field;
            fields[field] = fields[field] || [];
            fields[field].push(errors[i]);
          }
        }

        callback(errors, fields);
      }

      this.complete.push(complete);
      var idx = this.complete.length; // async validate

      (0, _util.asyncMap)(series, this._options, function (data, doIt) {
        var rule = data.rule;
        rule.field = data.field;

        function cb() {
          var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
          var errors = e;

          if (!Array.isArray(errors)) {
            errors = [errors];
          } // 自定义错误


          if (errors.length && rule.message) {
            errors = [].concat(rule.message);
          }

          errors = errors.map((0, _util.complementError)(rule));
          doIt(errors);
        }

        var res = rule.validator(rule, data.value, cb, _this._options);

        if (res && res.then) {
          res.then(function () {
            return cb();
          }, function (e) {
            return cb(e);
          });
        }
      }, function (results) {
        _this.complete[idx - 1](results);
      });
    }
  }]);

  return Schema;
}();

var _default = Schema;
exports["default"] = _default;