"use strict";

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

exports.__esModule = true;
exports.default = void 0;

var _has = _interopRequireDefault(require("lodash/has"));

var _isSchema = _interopRequireDefault(require("./util/isSchema"));

var Condition =
/*#__PURE__*/
function () {
  function Condition(refs, options) {
    this.refs = refs;

    if (typeof options === 'function') {
      this.fn = options;
      return;
    }

    if (!(0, _has.default)(options, 'is')) throw new TypeError('`is:` is required for `when()` conditions');
    if (!options.then && !options.otherwise) throw new TypeError('either `then:` or `otherwise:` is required for `when()` conditions');
    var is = options.is,
        then = options.then,
        otherwise = options.otherwise;
    var check = typeof is === 'function' ? is : function () {
      for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {
        values[_key] = arguments[_key];
      }

      return values.every(function (value) {
        return value === is;
      });
    };

    this.fn = function () {
      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }

      var options = args.pop();
      var schema = args.pop();
      var branch = check.apply(void 0, args) ? then : otherwise;
      if (!branch) return undefined;
      if (typeof branch === 'function') return branch(schema);
      return schema.concat(branch.resolve(options));
    };
  }

  var _proto = Condition.prototype;

  _proto.resolve = function resolve(base, options) {
    var values = this.refs.map(function (ref) {
      return ref.getValue(options);
    });
    var schema = this.fn.apply(base, values.concat(base, options));
    if (schema === undefined || schema === base) return base;
    if (!(0, _isSchema.default)(schema)) throw new TypeError('conditions must return a schema object');
    return schema.resolve(options);
  };

  return Condition;
}();

var _default = Condition;
exports.default = _default;
module.exports = exports["default"];