import { produce } from 'immer';

import village, { type VillageState } from '../village';
import build from './build';
import clear from './clear';
import pillage from './pillage';
import recruitUnits from './recruitUnits';
import startQuest from './startQuest';
import toggleMissionRepeat from './toggleMissionRepeat';
import upgradeBuilding from './upgradeBuilding';


// Encapsulates a move function into a store update, where the data is made
// immutable by immer. This allows moves to be much, much simpler to write,
// while ensuring that states are always immutable. We'll benefit from this
// when we want to implement an undo option.
export function makeMove(move: (...args: any[]) => boolean) {
    // Create a new function.
    return (...args: any[]) => {
        let result: boolean = false;

        // That updates the game state.
        village.update(state => {
            // With an immutable state.
            return produce(state, (V: VillageState) => {
                result = move(V, ...args);
            });
        });

        return result;
    };
}


export default {
    build: makeMove(build),
    clear: makeMove(clear),
    upgradeBuilding: makeMove(upgradeBuilding),
    pillage: makeMove(pillage),
    recruitUnits: makeMove(recruitUnits),
    startQuest: makeMove(startQuest),
    toggleMissionRepeat: makeMove(toggleMissionRepeat),
};
