"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SelfRef = void 0;
exports.selfref = selfref;

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

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

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

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

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

var _tsFns = require("ts-fns");

var _type = require("./type.js");

var _rules = require("./rules.js");

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2.default)(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2.default)(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2.default)(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

var SelfRef = /*#__PURE__*/function (_Type) {
  (0, _inherits2.default)(SelfRef, _Type);

  var _super = _createSuper(SelfRef);

  function SelfRef(fn) {
    var _this;

    (0, _classCallCheck2.default)(this, SelfRef);

    if (!(0, _tsFns.isFunction)(fn)) {
      throw new Error('[SelfRef]: pattern should be a function.');
    }

    _this = _super.call(this, null);
    _this.fn = fn;
    _this.name = 'SelfRef';
    _this._pattern = null;
    return _this;
  } // make pattern compute later


  (0, _createClass2.default)(SelfRef, [{
    key: "pattern",
    get: function get() {
      if (!this._pattern) {
        this._pattern = this.fn(this);
      }

      return this._pattern;
    } // leave for Type.constructor
    ,
    set: function set(v) {//.. do nothing
    }
  }, {
    key: "_decide",
    value: function _decide(value) {
      var type = (0, _rules.createType)(this.pattern);
      var error = type.catch(value);
      return error;
    }
  }, {
    key: "clone",
    value: function clone() {
      var Constructor = (0, _tsFns.getConstructorOf)(this);
      var ins = new Constructor(this.fn);
      return ins;
    }
  }]);
  return SelfRef;
}(_type.Type);

exports.SelfRef = SelfRef;

function selfref(fn) {
  var type = new SelfRef(fn);
  return type.init();
}