import { Cell } from "interface";
import { PlacePieceAction } from "./PlacePieceAction";

export class PlacePieceActionStack {
  readonly committedActions: PlacePieceAction[] = [];
  inProgressActions: PlacePieceAction[] = [];

  executeAction(action: PlacePieceAction, board: Cell[][]) {
    action.do(board);
    this.inProgressActions.push(action);
  }

  undoLastAction(board: Cell[][]) {
    const lastAction = this.inProgressActions.pop();
    if (!lastAction) {
      throw Error("No in progress action to undo");
    }
    lastAction.undo(board);
  }

  resetActions(board: Cell[][]) {
    try {
      while (true) {
        this.undoLastAction(board);
      }
    } catch (error) {
      if (
        !(error instanceof Error) ||
        error.message !== "No in progress action to undo"
      ) {
        throw error;
      }
    }
  }

  commitActions() {
    this.committedActions.push(...this.inProgressActions);
    this.inProgressActions = [];
  }
}
