'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var _classCallCheck = _interopDefault(require('@babel/runtime/helpers/classCallCheck'));
var _createClass = _interopDefault(require('@babel/runtime/helpers/createClass'));
var _defineProperty = _interopDefault(require('@babel/runtime/helpers/defineProperty'));
var utils = require('@forensic-js/utils');
var regex = require('@forensic-js/regex');
var StateException = _interopDefault(require('./Exceptions/StateException'));

var Common =
/*#__PURE__*/
function () {
  function Common() {
    _classCallCheck(this, Common);

    _defineProperty(this, "errors", {});

    _defineProperty(this, "status", true);

    _defineProperty(this, "field", '');

    _defineProperty(this, "options", {});

    _defineProperty(this, "index", 0);

    _defineProperty(this, "shouldProceed", true);
  }

  _createClass(Common, [{
    key: "reset",

    /**
     * resets the instance and makes it ready for the next validation process
     *
     * @param field next field to validate
     * @param options validation options
     * @param index field value index
     */
    value: function reset(field, options, index) {
      this.field = field;
      this.options = options;
      this.index = index;
      this.shouldProceed = true;
      this.status = true;
      return this;
    }
    /**
     * sets the given error message
     */

  }, {
    key: "setError",
    value: function setError(errorMessage, value) {
      var _this = this;

      if (this.status === false) {
        throw new StateException('cant set errors twice, did you forget to reset validator?');
      }

      if (!utils.isNumeric(value)) {
        value = "\"".concat(value, "\"");
      }

      this.errors[this.field] = regex.replaceCallback(/\{([^}]+)\}/, function (matches) {
        switch (matches[1].toLowerCase()) {
          case 'this':
            return value;

          case '_this':
            return _this.field;

          case '_index':
            return (_this.index + 1).toString();

          default:
            return matches[0];
        }
      }, errorMessage);
      return this.status = false;
    }
    /**
     * sets the error bag if given
     */

  }, {
    key: "setErrorBag",
    value: function setErrorBag(errorBag) {
      this.errors = errorBag;
      return this;
    }
    /**
     * returns the errobag object containing all errors
     */

  }, {
    key: "getErrorBag",
    value: function getErrorBag() {
      return this.errors;
    }
    /**
     * returns true if the last validation succeeded
     */

  }, {
    key: "succeeds",
    value: function succeeds() {
      return this.status;
    }
    /**
     * returns true if the last validation failed
     */

  }, {
    key: "fails",
    value: function fails() {
      return !this.succeeds();
    }
  }]);

  return Common;
}();

module.exports = Common;
//# sourceMappingURL=Common.js.map
