"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.WalletOperation = exports.MissedBlockDuringConfirmationError = void 0;
var rxjs_1 = require("rxjs");
var operators_1 = require("rxjs/operators");
var receipt_1 = require("./receipt");
var MissedBlockDuringConfirmationError = /** @class */ (function () {
    function MissedBlockDuringConfirmationError() {
        this.name = 'MissedBlockDuringConfirmationError';
        this.message = 'Taquito missed a block while waiting for operation confirmation and was not able to find the operation';
    }
    return MissedBlockDuringConfirmationError;
}());
exports.MissedBlockDuringConfirmationError = MissedBlockDuringConfirmationError;
var MAX_BRANCH_ANCESTORS = 60;
/**
 * @description WalletOperation allows to monitor operation inclusion on chains and surface information related to the operation
 */
var WalletOperation = /** @class */ (function () {
    /**
     *
     * @param opHash Operation hash
     * @param raw Raw operation that was injected
     * @param context Taquito context allowing access to rpc and signer
     */
    function WalletOperation(opHash, context, _newHead$) {
        var _this = this;
        this.opHash = opHash;
        this.context = context;
        this._newHead$ = _newHead$;
        this._operationResult = new rxjs_1.ReplaySubject(1);
        this._includedInBlock = new rxjs_1.ReplaySubject(1);
        this._included = false;
        this.newHead$ = this._newHead$.pipe(operators_1.tap(function (newHead) {
            if (!_this._included &&
                _this.lastHead &&
                newHead.header.level - _this.lastHead.header.level > 1) {
                throw new MissedBlockDuringConfirmationError();
            }
            _this.lastHead = newHead;
        }), operators_1.shareReplay({ bufferSize: 1, refCount: true }));
        // Observable that emit once operation is seen in a block
        this.confirmed$ = this.newHead$.pipe(operators_1.map(function (head) {
            var e_1, _a, e_2, _b;
            try {
                for (var _c = __values(head.operations), _d = _c.next(); !_d.done; _d = _c.next()) {
                    var opGroup = _d.value;
                    try {
                        for (var opGroup_1 = (e_2 = void 0, __values(opGroup)), opGroup_1_1 = opGroup_1.next(); !opGroup_1_1.done; opGroup_1_1 = opGroup_1.next()) {
                            var op = opGroup_1_1.value;
                            if (op.hash === _this.opHash) {
                                _this._included = true;
                                _this._includedInBlock.next(head);
                                _this._operationResult.next(op.contents);
                                // Return the block where the operation was found
                                return head;
                            }
                        }
                    }
                    catch (e_2_1) { e_2 = { error: e_2_1 }; }
                    finally {
                        try {
                            if (opGroup_1_1 && !opGroup_1_1.done && (_b = opGroup_1.return)) _b.call(opGroup_1);
                        }
                        finally { if (e_2) throw e_2.error; }
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
                }
                finally { if (e_1) throw e_1.error; }
            }
        }), operators_1.filter(function (x) {
            return typeof x !== 'undefined';
        }), operators_1.first(), operators_1.shareReplay({ bufferSize: 1, refCount: true }));
        this.confirmed$.pipe(operators_1.first()).subscribe();
    }
    WalletOperation.prototype.operationResults = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this._operationResult.pipe(operators_1.first()).toPromise()];
            });
        });
    };
    /**
     * @description Receipt expose the total amount of tezos token burn and spent on fees
     * The promise returned by receipt will resolve only once the transaction is included
     */
    WalletOperation.prototype.receipt = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = receipt_1.receiptFromOperation;
                        return [4 /*yield*/, this.operationResults()];
                    case 1: return [2 /*return*/, _a.apply(void 0, [_b.sent()])];
                }
            });
        });
    };
    WalletOperation.prototype.getCurrentConfirmation = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (!this._included) {
                    return [2 /*return*/, 0];
                }
                return [2 /*return*/, rxjs_1.combineLatest([this._includedInBlock, rxjs_1.from(this.context.rpc.getBlock())])
                        .pipe(operators_1.map(function (_a) {
                        var _b = __read(_a, 2), foundAtBlock = _b[0], head = _b[1];
                        return head.header.level - foundAtBlock.header.level + 1;
                    }), operators_1.first())
                        .toPromise()];
            });
        });
    };
    WalletOperation.prototype.isInCurrentBranch = function (tipBlockIdentifier) {
        if (tipBlockIdentifier === void 0) { tipBlockIdentifier = 'head'; }
        return __awaiter(this, void 0, void 0, function () {
            var tipBlockHeader, inclusionBlock, levelDiff, tipBlockLevel, blocks, _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        // By default it is assumed that the operation is in the current branch
                        if (!this._included) {
                            return [2 /*return*/, true];
                        }
                        return [4 /*yield*/, this.context.rpc.getBlockHeader({ block: tipBlockIdentifier })];
                    case 1:
                        tipBlockHeader = _b.sent();
                        return [4 /*yield*/, this._includedInBlock.pipe(operators_1.first()).toPromise()];
                    case 2:
                        inclusionBlock = _b.sent();
                        levelDiff = tipBlockHeader.level - inclusionBlock.header.level;
                        // Block produced before the operation is included are assumed to be part of the current branch
                        if (levelDiff <= 0) {
                            return [2 /*return*/, true];
                        }
                        tipBlockLevel = Math.min(inclusionBlock.header.level + levelDiff, inclusionBlock.header.level + MAX_BRANCH_ANCESTORS);
                        _a = Set.bind;
                        return [4 /*yield*/, this.context.rpc.getLiveBlocks({ block: String(tipBlockLevel) })];
                    case 3:
                        blocks = new (_a.apply(Set, [void 0, _b.sent()]))();
                        return [2 /*return*/, blocks.has(inclusionBlock.hash)];
                }
            });
        });
    };
    WalletOperation.prototype.confirmationObservable = function (confirmations) {
        var _this = this;
        if (typeof confirmations !== 'undefined' && confirmations < 1) {
            throw new Error('Confirmation count must be at least 1');
        }
        var defaultConfirmationCount = this.context.config.defaultConfirmationCount;
        var conf = confirmations !== undefined ? confirmations : defaultConfirmationCount;
        if (conf === undefined) {
            throw new Error('Default confirmation count can not be undefined!');
        }
        return rxjs_1.combineLatest([this._includedInBlock, this.newHead$]).pipe(operators_1.distinctUntilChanged(function (_a, _b) {
            var _c = __read(_a, 2), previousHead = _c[1];
            var _d = __read(_b, 2), newHead = _d[1];
            return previousHead.hash === newHead.hash;
        }), operators_1.map(function (_a) {
            var _b = __read(_a, 2), foundAtBlock = _b[0], head = _b[1];
            return {
                block: head,
                expectedConfirmation: conf,
                currentConfirmation: head.header.level - foundAtBlock.header.level + 1,
                completed: head.header.level - foundAtBlock.header.level >= conf - 1,
                isInCurrentBranch: function () { return _this.isInCurrentBranch(head.hash); },
            };
        }), operators_1.takeWhile(function (_a) {
            var completed = _a.completed;
            return !completed;
        }, true));
    };
    /**
     *
     * @param confirmations [0] Number of confirmation to wait for
     */
    WalletOperation.prototype.confirmation = function (confirmations) {
        return this.confirmationObservable(confirmations).toPromise();
    };
    return WalletOperation;
}());
exports.WalletOperation = WalletOperation;
//# sourceMappingURL=operation.js.map