import handleUserClicked from "./userpathhandler.ts";
import {State} from "./state";
import {
    Action,
    ID_ACTION_CLICKED_CELL,
    ID_ACTION_CLOSED_MESSAGE_BANNER,
    ID_ACTION_LOADED_MAZE,
    ID_ACTION_LOADING_FAILED,
    ID_ACTION_STARTED_LOADING,
    ID_ACTION_TOGGLED_SHOW_SOLUTION
} from "./action.ts";
import Maze from "@/app/model/maze.ts";

export default function reduce(state: State, action: Action): State {
    switch (action.type) {
        case ID_ACTION_STARTED_LOADING: {
            return {
                ...state,
                maze: null,
                loading: true,
                errorMessage: null
            }
        }
        case ID_ACTION_LOADED_MAZE: {
            return {
                ...state,
                loading: false,
                maze: action.maze as Maze,
                userPath: []
            }
        }
        case ID_ACTION_LOADING_FAILED: {
            return {
                ...state,
                loading: false,
                errorMessage: `Failed to load maze. Reason: ${action.reason}`
            }
        }
        case ID_ACTION_TOGGLED_SHOW_SOLUTION: {
            return {
                ...state,
                showSolution: action.value as boolean
            }
        }
        case ID_ACTION_CLOSED_MESSAGE_BANNER: {
            return {
                ...state,
                errorMessage: null
            }
        }
        case ID_ACTION_CLICKED_CELL: {
            // There's so much logic involved, externalize that into its own file.
            return handleUserClicked(state, action.x as number, action.y as number);
        }
        default: {
            throw new Error(`Unknown action: ${action.type}`);
        }
    }
}