package dev.bytevibe.hyperpoint;

import java.util.Stack;

/**
 * 命令历史管理器，支持撤销和重做
 */
public class CommandHistory {
    private Stack<Command> undoStack;
    private Stack<Command> redoStack;
    private Runnable onHistoryChanged;

    public CommandHistory() {
        this.undoStack = new Stack<>();
        this.redoStack = new Stack<>();
    }

    /**
     * 执行命令并将其添加到历史记录
     */
    public void execute(Command command) {
        command.execute();
        undoStack.push(command);
        redoStack.clear();  // 执行新命令后，清空重做栈
        notifyHistoryChanged();
    }

    /**
     * 撤销上一个命令
     */
    public void undo() {
        if (!undoStack.isEmpty()) {
            Command command = undoStack.pop();
            command.undo();
            redoStack.push(command);
            notifyHistoryChanged();
        }
    }

    /**
     * 重做上一个被撤销的命令
     */
    public void redo() {
        if (!redoStack.isEmpty()) {
            Command command = redoStack.pop();
            command.execute();
            undoStack.push(command);
            notifyHistoryChanged();
        }
    }

    /**
     * 检查是否可以撤销
     */
    public boolean canUndo() {
        return !undoStack.isEmpty();
    }

    /**
     * 检查是否可以重做
     */
    public boolean canRedo() {
        return !redoStack.isEmpty();
    }

    /**
     * 清空历史记录
     */
    public void clear() {
        undoStack.clear();
        redoStack.clear();
        notifyHistoryChanged();
    }

    /**
     * 设置历史记录变化监听器
     */
    public void setOnHistoryChanged(Runnable callback) {
        this.onHistoryChanged = callback;
    }

    /**
     * 通知历史记录已改变
     */
    private void notifyHistoryChanged() {
        if (onHistoryChanged != null) {
            onHistoryChanged.run();
        }
    }
}

