"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 (g && (g = 0, op[0] && (_ = 0)), _) 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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsyncOperationStatus = exports.UPDATE_ASYNC_OPERATION_REALTIME_EVENT = void 0;
var async_operation_status_1 = require("@bringg/types/types/async_operation_status");
var BringgException_1 = require("../Core/BringgException");
var ExceptionReason_1 = require("../Core/ExceptionReason");
var realtime_subscriptions_1 = __importDefault(require("../realtime-subscriptions"));
var abort_1 = require("../utils/abort");
var promises_1 = require("../utils/promises");
exports.UPDATE_ASYNC_OPERATION_REALTIME_EVENT = 'async operation status';
var AsyncOperationStatus = /** @class */ (function () {
    function AsyncOperationStatus(session) {
        var _this = this;
        // In case of adding listener for a request that status update was already received, we will save that so nothing will be lost
        this.unackedStatusUpdates = new Map();
        this.listeners = new Map();
        this.cleanupUnackedMessageThatPassedTTL = function () {
            var e_1, _a;
            var now = Date.now();
            try {
                for (var _b = __values(_this.unackedStatusUpdates), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var _d = __read(_c.value, 2), key = _d[0], queue = _d[1];
                    var liveMessages = queue.filter(function (_a) {
                        var messageTimeInMs = _a.messageTimeInMs;
                        return now - messageTimeInMs < AsyncOperationStatus.UNACKED_MESSAGES_TTL;
                    });
                    // If there are no live messages, we can remove the whole queue (this shouldn't happen as we have a check for this earlier
                    if (liveMessages.length === 0) {
                        _this.unackedStatusUpdates.delete(key);
                    }
                    else {
                        // Only keep the live messages
                        _this.unackedStatusUpdates.set(key, liveMessages);
                    }
                }
            }
            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; }
            }
        };
        this.realtimeSubscriptions = new realtime_subscriptions_1.default(session);
        this.listenToEvent();
        this.cleanupInterval = setInterval(this.cleanupUnackedMessageThatPassedTTL, AsyncOperationStatus.UNACKED_MESSAGES_TTL);
    }
    AsyncOperationStatus.prototype.listenToEvent = function () {
        var _this = this;
        this.unsubscribe = this.realtimeSubscriptions.subscribe(exports.UPDATE_ASYNC_OPERATION_REALTIME_EVENT, function (event) {
            var listener = _this.listeners.get(event.request_id);
            if (listener) {
                try {
                    listener(event);
                }
                catch (_a) {
                    // ignore
                }
                return;
            }
            var queue = _this.unackedStatusUpdates.get(event.request_id);
            if (!queue) {
                queue = [];
                _this.unackedStatusUpdates.set(event.request_id, queue);
            }
            queue.push({
                event: event,
                messageTimeInMs: Date.now()
            });
            return;
        });
    };
    AsyncOperationStatus.prototype.addListener = function (_a) {
        var requestId = _a.requestId, handler = _a.handler, signal = _a.signal, _b = _a.once, once = _b === void 0 ? false : _b;
        return once
            ? this._once({ requestId: requestId, handler: handler, signal: signal, once: once })
            : this._addListener({ requestId: requestId, handler: handler, signal: signal });
    };
    AsyncOperationStatus.prototype._addListener = function (_a) {
        var e_2, _b;
        var _this = this;
        var requestId = _a.requestId, handler = _a.handler, signal = _a.signal;
        if (signal.aborted) {
            return;
        }
        if (this.listeners.has(requestId)) {
            // eslint-disable-next-line no-console
            console.warn("Listener for request ".concat(requestId, " already exists"));
        }
        var abortedInTheMiddle = false;
        if (this.unackedStatusUpdates.has(requestId)) {
            var unackedStatusUpdates = this.unackedStatusUpdates.get(requestId);
            var processedMessages = 0;
            try {
                for (var unackedStatusUpdates_1 = __values(unackedStatusUpdates), unackedStatusUpdates_1_1 = unackedStatusUpdates_1.next(); !unackedStatusUpdates_1_1.done; unackedStatusUpdates_1_1 = unackedStatusUpdates_1.next()) {
                    var event_1 = unackedStatusUpdates_1_1.value.event;
                    abortedInTheMiddle = signal.aborted;
                    if (abortedInTheMiddle) {
                        break;
                    }
                    try {
                        handler(event_1);
                    }
                    catch (_c) {
                        // ignore
                    }
                    processedMessages++;
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (unackedStatusUpdates_1_1 && !unackedStatusUpdates_1_1.done && (_b = unackedStatusUpdates_1.return)) _b.call(unackedStatusUpdates_1);
                }
                finally { if (e_2) throw e_2.error; }
            }
            if (abortedInTheMiddle) {
                // Remove the processed messages
                unackedStatusUpdates.splice(0, processedMessages);
            }
            else {
                this.unackedStatusUpdates.delete(requestId);
            }
        }
        if (signal.aborted) {
            return;
        }
        // Because we call the handlers synchronously, it is ok that we add the listener afterwards
        // If we would wait for the handler this would have be needed to move before handling the unacked messages
        this.listeners.set(requestId, handler);
        signal.addEventListener('abort', function () {
            _this.listeners.delete(requestId);
        }, { once: true });
    };
    AsyncOperationStatus.prototype._once = function (_a) {
        var requestId = _a.requestId, handler = _a.handler, signal = _a.signal;
        if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
            return;
        }
        // Merge the signal with the signal of the once cleanup
        var mergedAc = new AbortController();
        function handlerWrapper(payload) {
            // Cleaning up the listener, must be before calling the handler as it might throw
            mergedAc.abort();
            return handler(payload);
        }
        // Propagate the abort event to the merged signal
        signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', mergedAc.abort.bind(mergedAc), {
            once: true,
            // Cleanup this listener when the mergedAc is aborted
            signal: mergedAc.signal
        });
        this._addListener({ requestId: requestId, handler: handlerWrapper, signal: mergedAc.signal });
    };
    /**
     * This is suitable for cases where the user send a request in HTTP and should get the response in realtime
     */
    AsyncOperationStatus.prototype.waitForResponse = function (_a) {
        var requestId = _a.requestId, signal = _a.signal, timeoutInMs = _a.timeoutInMs;
        return __awaiter(this, void 0, void 0, function () {
            function handler(_a) {
                var status = _a.status, payload = _a.payload;
                abortReason = 'already-fulfilled';
                mergedAc.abort();
                if (status === async_operation_status_1.AsyncOperationStatusType.FAILURE) {
                    reject(new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.UNSUCCESSFUL_RESULT, "Got unsuccessful result for request id ".concat(requestId), undefined, payload));
                }
                else {
                    resolve(payload);
                }
            }
            function onSignalInputAborted() {
                abortReason = 'abort';
                mergedAc.abort();
            }
            var timeout, abortReason, _b, promise, resolve, reject, mergedAc;
            return __generator(this, function (_c) {
                if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
                    (0, abort_1.throwAbortError)(signal);
                }
                _b = (0, promises_1.createDeferredPromise)(), promise = _b.promise, resolve = _b.resolve, reject = _b.reject;
                mergedAc = new AbortController();
                mergedAc.signal.addEventListener('abort', function () {
                    switch (abortReason) {
                        // Handled manually
                        case 'already-fulfilled':
                            return;
                        case 'abort':
                            reject((0, abort_1.createAbortError)(signal));
                            return;
                        case 'timeout':
                            reject(new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.TIMEOUT, "Timeout of ".concat(timeoutInMs, "ms exceeded while waiting for response for request id ").concat(requestId)));
                            return;
                        // This will happen on resolve
                        default:
                            return;
                    }
                });
                this._addListener({ requestId: requestId, handler: handler, signal: mergedAc.signal });
                // Can happen when have unacked messages
                if (!mergedAc.signal.aborted) {
                    // Propagate the abort event to the merged signal
                    signal === null || signal === void 0 ? void 0 : signal.addEventListener('abort', onSignalInputAborted, {
                        once: true
                    });
                    if (timeoutInMs) {
                        timeout = setTimeout(function () {
                            abortReason = 'timeout';
                            mergedAc.abort();
                        }, timeoutInMs);
                    }
                }
                return [2 /*return*/, promise.finally(function () {
                        signal === null || signal === void 0 ? void 0 : signal.removeEventListener('abort', onSignalInputAborted);
                        clearTimeout(timeout);
                    })];
            });
        });
    };
    AsyncOperationStatus.prototype.hasUnackedStatusUpdates = function () {
        return this.unackedStatusUpdates.size > 0;
    };
    AsyncOperationStatus.prototype.unregisterCleanUnackedMessage = function () {
        clearInterval(this.cleanupInterval);
        this.cleanupInterval = undefined;
    };
    AsyncOperationStatus.prototype.cleanup = function () {
        var _a;
        this.unregisterCleanUnackedMessage();
        (_a = this.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(this);
        this.unsubscribe = undefined;
        this.listeners.clear();
        this.unackedStatusUpdates.clear();
    };
    AsyncOperationStatus.UNACKED_MESSAGES_TTL = 1000 * 60 * 3; // 3 minutes
    return AsyncOperationStatus;
}());
exports.AsyncOperationStatus = AsyncOperationStatus;
//# sourceMappingURL=AsyncOperationStatus.js.map