"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AnnalsController = void 0;
const WebUndo_1 = require("./WebUndo");
const tree_dump_1 = require("tree-dump");
class AnnalsController {
    constructor(opts) {
        this.opts = opts;
        this.manager = new WebUndo_1.WebUndo();
        this.captured = new WeakSet();
        this._undo = (doPatch) => {
            const { log, et } = this.opts;
            const patch = log.undo(doPatch);
            et.dispatch('annals', {
                action: 'undo',
                batch: [patch],
            });
            // console.log('doPatch', doPatch + '');
            // console.log('undoPatch', patch + '');
            return [doPatch, this._redo];
        };
        this._redo = (doPatch) => {
            const { log, et } = this.opts;
            const redoPatch = doPatch.rebase(log.end.clock.time);
            et.dispatch('annals', {
                action: 'redo',
                batch: [redoPatch],
            });
            // console.log('doPatch', doPatch + '');
            // console.log('redoPatch', redoPatch + '');
            return [redoPatch, this._undo];
        };
    }
    /** ------------------------------------------------- {@link UndoCollector} */
    capture() {
        const currentPatch = this.opts.txt.model.api.builder.patch;
        this.captured.add(currentPatch);
    }
    undo() {
        this.manager.undo();
    }
    redo() {
        this.manager.redo();
    }
    /** -------------------------------------------------- {@link UiLifeCycles} */
    start() {
        const stopManager = this.manager.start();
        const { opts, captured } = this;
        const { txt } = opts;
        txt.model.api.onFlush.listen((patch) => {
            const isCaptured = captured.has(patch);
            if (isCaptured) {
                captured.delete(patch);
                const item = [patch, this._undo];
                this.manager.push(item);
            }
        });
        return () => {
            stopManager();
        };
    }
    /** ----------------------------------------------------- {@link Printable} */
    toString(tab) {
        return ('annals' +
            (0, tree_dump_1.printTree)(tab, [(tab) => 'undo: ' + this.manager.uStack.length, (tab) => 'redo: ' + this.manager.rStack.length]));
    }
}
exports.AnnalsController = AnnalsController;
//# sourceMappingURL=AnnalsController.js.map