import React, { createContext, PropsWithChildren, useEffect, useReducer } from "react";
import { Tabletop } from "visions-types";
import { assertNever } from "../plugins/Candela";

type AuthState = { type: "NoAdmin" } | { type: "Unauthed" } | { type: "Authed", username: string };

type TabletopState = {
    auth: AuthState;
    tabletop: Tabletop;
}

type StateAction = { type: "SetAuthState", state: AuthState }
                   | { type: "HandleMessage" };

const initialState = (): TabletopState => (
    {
        auth: { type: "Unauthed" },
        tabletop: { backgroundColor: { red: 0, green: 0, blue: 0 }, backgroundImage: undefined }
    }
);

export const AppContext = createContext<TabletopState>(initialState());

interface StateProviderProps { }

export const StateProvider = ({ children }: PropsWithChildren<StateProviderProps>) => {
    const [state, dispatch] = useReducer(stateReducer, initialState());

    return <AppContext.Provider value={initialState()}>
        {children}
    </AppContext.Provider>;
}

const stateReducer = (state: TabletopState, action: StateAction): TabletopState => {
    switch (action.type) {
        case "SetAuthState": {
            return { ...state, auth: action.state };
        }
        case "HandleMessage": {
            return state;
        }
        default: {
            assertNever(action);
            return state;
        }
    }
}