import 'package:logging/logging.dart'; import 'game_event.dart'; import 'state/game_state.dart'; final _log = Logger('ActionHandler'); /// Executes commands and maintains undo/redo history. /// /// Server port of the reference app's `ActionHandler`: the `ValueNotifier`s /// are plain fields, and the server/client branching is gone — this process /// is always the server, so every action runs locally, saves, and notifies /// the (Phase 2) broadcast hook [onAction]. class ActionHandler { int commandIndex = -1; final List _commands = []; final List _commandDescriptions = []; final List _gameSaveStates = []; List get commands => List.unmodifiable(_commands); List get commandDescriptions => List.unmodifiable(_commandDescriptions); List get gameSaveStates => List.unmodifiable(_gameSaveStates); /// The event produced by the most recent state transition. /// /// Set before [commandIndex] changes so that listeners can read the /// correct event during their rebuild. GameEvent lastEvent = const NoEvent(); final int maxUndo = 250; final GameState _gameState; /// Set by the network layer (Phase 2); null in tests. /// /// Invoked after every action/undo/redo with the new command index, the /// action's `describe()` string, and the serialized [GameEvent] — the /// pieces the reference app put into its `{i, d, e, s}` envelope. void Function(int index, String description, String eventJson)? onAction; ActionHandler({required GameState gameState}) : _gameState = gameState; /// Resets all command/description/save-state history to a clean slate, /// keeping only the most recent save state as the baseline. void resetCommandHistory() { _commands.clear(); _commandDescriptions.clear(); if (_gameSaveStates.length > 1) { _gameSaveStates.removeRange(0, _gameSaveStates.length - 1); } } /// Clears only the local commands list. void clearLocalCommands() { _commands.clear(); } /// Inserts a description received from the network at [index]. void insertReceivedDescription(int index, String description) { _commandDescriptions.insert(index, description); } /// Appends a save-state snapshot. Called by [GameState.save] and [GameState.load]. void addSaveState(GameSaveState state) { _gameSaveStates.add(state); } void updateAllUI() { _gameState.notifyListeners(); _gameState.notifyAllMonsterInstances(); } Command getCurrent() { final cmd = _commands[commandIndex]; if (cmd == null) throw StateError('No command at index $commandIndex'); return cmd; } void undo() { if (commandIndex >= 0) { // Guard against out-of-bounds access: in the server multiplayer path // updateStateFromMessage sets commandIndex directly then calls save() // once, which can leave commandIndex >= gameSaveStates.length. final saveState = commandIndex < _gameSaveStates.length ? _gameSaveStates[commandIndex] : null; if (saveState != null) { saveState.load(_gameState); saveState.saveToDisk(_gameState); updateAllUI(); } lastEvent = const NoEvent(); // The broadcast travels the undone action's description (as the // reference's undo envelope does) but the *post-decrement* index: the // reference reports the pre-decrement index because its clients keep // local state and reconcile it; our stateless web clients take the // wire index at face value, so it must equal the state position. final undoneDescription = commandIndex < _commandDescriptions.length ? _commandDescriptions[commandIndex] : ''; commandIndex--; if (saveState != null) _sendState('undo', description: undoneDescription); } } void redo() { if (commandIndex < _commandDescriptions.length - 1) { lastEvent = const NoEvent(); commandIndex++; final nextIdx = commandIndex + 1; final nextState = (nextIdx < _gameSaveStates.length) ? _gameSaveStates[nextIdx] : null; if (nextState == null) return; // save state evicted by maxUndo nextState.load(_gameState); nextState.saveToDisk(_gameState); //also run generic update ui function updateAllUI(); } _sendState('redo'); } /// Broadcasts the current command index + description after an undo/redo, /// mirroring the reference app's server-side `StateEnvelope` send. /// [description] overrides the one at the current index (the undo path /// sends the undone action's name; the redo path sends the redone one). void _sendState(String action, {String? description}) { final idx = commandIndex; // idx -1 is the baseline (empty history). The reference skips the send // there because its clients keep local state; the stateless web clients // only ever see what the server pushes, so the baseline goes out too. if (idx >= -1 && idx < _commandDescriptions.length) { final desc = description ?? (idx >= 0 ? _commandDescriptions[idx] : ''); _log.info('server sends, $action index: $idx, description:$desc'); onAction?.call(idx, desc, const NoEvent().toJsonString()); } } void action(Command command) { command.execute(); if (_commands.length > commandIndex) { _commands.insert(commandIndex + 1, command); _commandDescriptions.insert(commandIndex + 1, command.describe()); } else { _commands.add(command); _commandDescriptions.add(command.describe()); } // Set event before commandIndex changes so listener callbacks see the // correct value. lastEvent = command.event; commandIndex++; //remove possible redo list if (_commands.length - 1 > commandIndex) { _commands.removeRange(commandIndex + 1, _commands.length); _commandDescriptions.removeRange( commandIndex + 1, _commandDescriptions.length, ); } if (_gameSaveStates.length > commandIndex + 1) { //remove future game states _gameSaveStates.removeRange(commandIndex + 1, _gameSaveStates.length); } _gameState.save(); //save after each action //send last game state if connected String description = command.describe(); String eventJson = command.event.toJsonString(); _log.info('server sends, index: $commandIndex, description:$description'); onAction?.call(commandIndex, description, eventJson); //TODO: this is breaking if command index is not in sync with commands. and in connected state. //really need to go over this again: do we really need to save commands at all, or are save states + descriptions enough also for offline? if (commandIndex >= maxUndo) { if (_commands.length > commandIndex) { _commands[commandIndex - maxUndo] = null; } if (_gameSaveStates.length > commandIndex - maxUndo) { _gameSaveStates[commandIndex - maxUndo] = null; } } } }