"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.undoableCommand = exports.UndoableCommand = exports.UndoableCommandController = void 0;
const __1 = require("..");
class UndoableCommandController {
    constructor(historySize = 10) {
        this.historySize = historySize;
        this.history = [];
    }
    undoLast() {
        var _a;
        const result = this.history.pop();
        if (result) {
            (_a = result === null || result === void 0 ? void 0 : result.undo) === null || _a === void 0 ? void 0 : _a.call(result);
        }
        return result;
    }
    addEntry(result) {
        if (!result.undo)
            this.history.push(result);
        if (this.history.length >= this.historySize) {
            this.history.shift();
        }
    }
}
exports.UndoableCommandController = UndoableCommandController;
class UndoableCommand extends __1.Command {
}
exports.UndoableCommand = UndoableCommand;
const undoableCommand = (controller = new UndoableCommandController()) => (onExecute) => {
    return ((data, context) => {
        const result = onExecute
            ? onExecute(data, context)
            : context.handler(data, context.options);
        if (!(result === null || result === void 0 ? void 0 : result.undo)) {
            throw new Error('UndoableCommandHandler must return an undo function');
        }
        controller.addEntry({
            value: result.value,
            name: result.name,
            undo: result.undo,
        });
        return result;
    });
};
exports.undoableCommand = undoableCommand;
//# sourceMappingURL=undoableCommand.js.map