"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
    for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
        to[j] = from[i];
    return to;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.hexBytes = exports.parseHex = exports.parseDate = exports.isPairData = exports.isPairType = exports.unpackComb = exports.encodeTezosID = exports.checkDecodeTezosID = exports.tezosPrefix = exports.unpackAnnotations = exports.isNatural = exports.isDecimal = exports.compareBytes = exports.parseBytes = exports.LongInteger = exports.MichelsonTypeError = exports.isMichelsonError = exports.MichelsonError = void 0;
var base58_1 = require("./base58");
var MichelsonError = /** @class */ (function (_super) {
    __extends(MichelsonError, _super);
    /**
     * @param val Value of a AST node caused the error
     * @param path Path to a node caused the error
     * @param message An error message
     */
    function MichelsonError(val, message) {
        var _this = _super.call(this, message) || this;
        _this.val = val;
        Object.setPrototypeOf(_this, MichelsonError.prototype);
        return _this;
    }
    return MichelsonError;
}(Error));
exports.MichelsonError = MichelsonError;
function isMichelsonError(err) {
    return err instanceof MichelsonError;
}
exports.isMichelsonError = isMichelsonError;
var MichelsonTypeError = /** @class */ (function (_super) {
    __extends(MichelsonTypeError, _super);
    /**
     * @param val Value of a type node caused the error
     * @param data Value of a data node caused the error
     * @param message An error message
     */
    function MichelsonTypeError(val, data, message) {
        var _this = _super.call(this, val, message) || this;
        if (data !== undefined) {
            _this.data = data;
        }
        Object.setPrototypeOf(_this, MichelsonTypeError.prototype);
        return _this;
    }
    return MichelsonTypeError;
}(MichelsonError));
exports.MichelsonTypeError = MichelsonTypeError;
// Ad hoc big integer parser
var LongInteger = /** @class */ (function () {
    function LongInteger(arg) {
        this.neg = false;
        this.buf = [];
        if (arg === undefined) {
            return;
        }
        if (typeof arg === "string") {
            for (var i = 0; i < arg.length; i++) {
                var c = arg.charCodeAt(i);
                if (i === 0 && c === 0x2d) {
                    this.neg = true;
                }
                else {
                    if (c < 0x30 || c > 0x39) {
                        throw new Error("unexpected character in integer constant: " + arg[i]);
                    }
                    this.append(c - 0x30);
                }
            }
        }
        else if (arg < 0) {
            this.neg = true;
            this.append(-arg);
        }
        else {
            this.append(arg);
        }
    }
    LongInteger.prototype.append = function (c) {
        var i = 0;
        while (c !== 0 || i < this.buf.length) {
            var m = (this.buf[i] || 0) * 10 + c;
            this.buf[i++] = m % 256;
            c = Math.floor(m / 256);
        }
    };
    LongInteger.prototype.cmp = function (arg) {
        if (this.neg !== arg.neg) {
            return (arg.neg ? 1 : 0) - (this.neg ? 1 : 0);
        }
        else {
            var ret = 0;
            if (this.buf.length !== arg.buf.length) {
                ret = this.buf.length < arg.buf.length ? -1 : 1;
            }
            else if (this.buf.length !== 0) {
                var i = arg.buf.length - 1;
                while (i >= 0 && this.buf[i] === arg.buf[i]) {
                    i--;
                }
                ret = i < 0 ? 0 : this.buf[i] < arg.buf[i] ? -1 : 1;
            }
            return !this.neg ? ret : ret === 0 ? 0 : -ret;
        }
    };
    Object.defineProperty(LongInteger.prototype, "sign", {
        get: function () {
            return this.buf.length === 0 ? 0 : this.neg ? -1 : 1;
        },
        enumerable: false,
        configurable: true
    });
    return LongInteger;
}());
exports.LongInteger = LongInteger;
function parseBytes(s) {
    var ret = [];
    for (var i = 0; i < s.length; i += 2) {
        var x = parseInt(s.slice(i, i + 2), 16);
        if (Number.isNaN(x)) {
            return null;
        }
        ret.push(x);
    }
    return ret;
}
exports.parseBytes = parseBytes;
function compareBytes(a, b) {
    if (a.length !== b.length) {
        return a.length < b.length ? -1 : 1;
    }
    else if (a.length !== 0) {
        var i = 0;
        while (i < a.length && a[i] === b[i]) {
            i++;
        }
        return i === a.length ? 0 : a[i] < b[i] ? -1 : 1;
    }
    else {
        return 0;
    }
}
exports.compareBytes = compareBytes;
function isDecimal(x) {
    try {
        // tslint:disable-next-line: no-unused-expression
        new LongInteger(x);
        return true;
    }
    catch (_a) {
        return false;
    }
}
exports.isDecimal = isDecimal;
function isNatural(x) {
    try {
        return new LongInteger(x).sign >= 0;
    }
    catch (_a) {
        return false;
    }
}
exports.isNatural = isNatural;
var annRe = /^(@%|@%%|%@|[@:%]([_0-9a-zA-Z][_0-9a-zA-Z\.%@]*)?)$/;
function unpackAnnotations(p, opt) {
    var e_1, _a;
    if (Array.isArray(p)) {
        return {};
    }
    var field;
    var type;
    var vars;
    if (p.annots !== undefined) {
        try {
            for (var _b = __values(p.annots), _c = _b.next(); !_c.done; _c = _b.next()) {
                var v = _c.value;
                if (v.length !== 0) {
                    if (!annRe.test(v) ||
                        (!(opt === null || opt === void 0 ? void 0 : opt.specialVar) && (v === "@%" || v === "@%%")) ||
                        (!(opt === null || opt === void 0 ? void 0 : opt.specialFields) && v === "%@")) {
                        throw new MichelsonError(p, p.prim + ": unexpected annotation: " + v);
                    }
                    switch (v[0]) {
                        case "%":
                            if ((opt === null || opt === void 0 ? void 0 : opt.emptyFields) || v.length > 1) {
                                field = field || [];
                                field.push(v);
                            }
                            break;
                        case ":":
                            if (v.length > 1) {
                                type = type || [];
                                type.push(v);
                            }
                            break;
                        case "@":
                            if ((opt === null || opt === void 0 ? void 0 : opt.emptyVar) || v.length > 1) {
                                vars = vars || [];
                                vars.push(v);
                            }
                            break;
                    }
                }
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
            }
            finally { if (e_1) throw e_1.error; }
        }
    }
    return { f: field, t: type, v: vars };
}
exports.unpackAnnotations = unpackAnnotations;
exports.tezosPrefix = {
    BlockHash: [32, [1, 52]],
    OperationHash: [32, [5, 116]],
    OperationListHash: [32, [133, 233]],
    OperationListListHash: [32, [29, 159, 109]],
    ProtocolHash: [32, [2, 170]],
    ContextHash: [32, [79, 199]],
    ED25519PublicKeyHash: [20, [6, 161, 159]],
    SECP256K1PublicKeyHash: [20, [6, 161, 161]],
    P256PublicKeyHash: [20, [6, 161, 164]],
    ContractHash: [20, [2, 90, 121]],
    CryptoboxPublicKeyHash: [16, [153, 103]],
    ED25519Seed: [32, [13, 15, 58, 7]],
    ED25519PublicKey: [32, [13, 15, 37, 217]],
    SECP256K1SecretKey: [32, [17, 162, 224, 201]],
    P256SecretKey: [32, [16, 81, 238, 189]],
    ED25519EncryptedSeed: [56, [7, 90, 60, 179, 41]],
    SECP256K1EncryptedSecretKey: [56, [9, 237, 241, 174, 150]],
    P256EncryptedSecretKey: [56, [9, 48, 57, 115, 171]],
    SECP256K1PublicKey: [33, [3, 254, 226, 86]],
    P256PublicKey: [33, [3, 178, 139, 127]],
    SECP256K1Scalar: [33, [38, 248, 136]],
    SECP256K1Element: [33, [5, 92, 0]],
    ED25519SecretKey: [64, [43, 246, 78, 7]],
    ED25519Signature: [64, [9, 245, 205, 134, 18]],
    SECP256K1Signature: [64, [13, 115, 101, 19, 63]],
    P256Signature: [64, [54, 240, 44, 52]],
    GenericSignature: [64, [4, 130, 43]],
    ChainID: [4, [87, 82, 0]],
};
function checkDecodeTezosID(id) {
    var e_2, _a;
    var types = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        types[_i - 1] = arguments[_i];
    }
    var buf = base58_1.decodeBase58Check(id);
    try {
        for (var types_1 = __values(types), types_1_1 = types_1.next(); !types_1_1.done; types_1_1 = types_1.next()) {
            var t = types_1_1.value;
            var _b = __read(exports.tezosPrefix[t], 2), plen = _b[0], p = _b[1];
            if (buf.length === plen + p.length) {
                var i = 0;
                while (i < p.length && buf[i] === p[i]) {
                    i++;
                }
                if (i === p.length) {
                    return [t, buf.slice(p.length)];
                }
            }
        }
    }
    catch (e_2_1) { e_2 = { error: e_2_1 }; }
    finally {
        try {
            if (types_1_1 && !types_1_1.done && (_a = types_1.return)) _a.call(types_1);
        }
        finally { if (e_2) throw e_2.error; }
    }
    return null;
}
exports.checkDecodeTezosID = checkDecodeTezosID;
function encodeTezosID(id, data) {
    var _a = __read(exports.tezosPrefix[id], 2), plen = _a[0], p = _a[1];
    if (data.length !== plen) {
        throw new Error("incorrect data length for " + id + ": " + data.length);
    }
    return base58_1.encodeBase58Check(__spreadArray(__spreadArray([], __read(p)), __read(data)));
}
exports.encodeTezosID = encodeTezosID;
function unpackComb(id, v) {
    var vv = v;
    var args = Array.isArray(vv) ? vv : vv.args;
    if (args.length === 2) {
        // it's a way to make a union of two interfaces not an interface with two independent properties of union types
        var ret = id === "pair" ? {
            prim: "pair",
            args: args,
        } : {
            prim: "Pair",
            args: args,
        };
        return ret;
    }
    return __assign(__assign({}, (Array.isArray(vv) ? { prim: id } : vv)), { args: [
            args[0],
            {
                prim: id,
                args: args.slice(1),
            },
        ] });
}
exports.unpackComb = unpackComb;
function isPairType(t) {
    return Array.isArray(t) || t.prim === "pair";
}
exports.isPairType = isPairType;
function isPairData(d) {
    return Array.isArray(d) || "prim" in d && d.prim === "Pair";
}
exports.isPairData = isPairData;
var rfc3339Re = /^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])[T ]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|[+-]([01][0-9]|2[0-3]):([0-5][0-9]))$/;
function parseDate(a) {
    if ("string" in a) {
        if (isNatural(a.string)) {
            return new Date(parseInt(a.string, 10));
        }
        else if (rfc3339Re.test(a.string)) {
            var x = new Date(a.string);
            if (!Number.isNaN(x.valueOf)) {
                return x;
            }
        }
    }
    else if (isNatural(a.int)) {
        return new Date(parseInt(a.int, 10));
    }
    return null;
}
exports.parseDate = parseDate;
function parseHex(s) {
    var res = [];
    for (var i = 0; i < s.length; i += 2) {
        var ss = s.slice(i, i + 2);
        var x = parseInt(ss, 16);
        if (Number.isNaN(x)) {
            throw new Error("can't parse hex byte: " + ss);
        }
        res.push(x);
    }
    return res;
}
exports.parseHex = parseHex;
function hexBytes(bytes) {
    return bytes.map(function (x) { return ((x >> 4) & 0xf).toString(16) + (x & 0xf).toString(16); }).join("");
}
exports.hexBytes = hexBytes;
//# sourceMappingURL=utils.js.map