"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Timeline = void 0;
class Timeline {
    constructor() {
        this.timeline = [];
        this.stop = false;
        this.executor = null;
    }
    put(time, entry) {
        this.timeline.push([time, [entry]]);
        this.timeline.sort((a, b) => a[0].getTime() - b[0].getTime());
    }
    runAndRemoveEntriesBefore(time, func) {
        const timesToRemove = [];
        for (let i = 0; i < this.timeline.length; i++) {
            const [entryTime, entries] = this.timeline[i];
            if (entryTime < time) {
                timesToRemove.push(entryTime);
                for (const entry of entries) {
                    func(entry);
                }
            }
            else {
                break;
            }
        }
        for (const timeToRemove of timesToRemove) {
            const index = this.timeline.findIndex(([key]) => key === timeToRemove);
            if (index !== -1) {
                this.timeline.splice(index, 1);
            }
        }
    }
    process(func) {
        return __awaiter(this, void 0, void 0, function* () {
            this.stop = false;
            this.executor = new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
                while (!this.stop && this.timeline.length > 0) {
                    this.runAndRemoveEntriesBefore(new Date(), func);
                    if (this.timeline.length === 0) {
                        resolve();
                        return;
                    }
                    yield new Promise((resolve) => setTimeout(resolve, 1000));
                }
                resolve();
            }));
            yield this.executor;
        });
    }
    waitForProcessing() {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.executor) {
                yield this.executor;
            }
        });
    }
    cancel() {
        this.stop = true;
    }
    clear() {
        this.timeline = [];
    }
    toString() {
        let sb = '';
        for (const [t, entries] of this.timeline) {
            sb += t + ' -> ' + entries;
        }
        return sb;
    }
}
exports.Timeline = Timeline;
//# sourceMappingURL=Timeline.js.map