import {Dispatch, useMemo, useReducer} from "react";
import {appStateReducer} from "../reducers/AppStateReducer";
import {AppState} from "../state/AppState";
import {ServerConnectionState} from "../state/NetworkState";
import {sizeFromLinesAndCells} from "../../../common/src/state/Coordinates";
import {AppAction} from "../../../common/src/actions/AppAction";
import {USER_ACTIVE_COLOR} from "../../../common/src/actions/UserAction";
import HexColorPicker from "./HexColorPicker";
import HexMapRenderer from "./HexMapRenderer";
import {DispatchContext} from "./context/DispatchContext";
import "./App.css";
import {WebsocketReactAdapter} from "./WebsocketReactAdapter";

function App() {
    const defaultState: AppState = {
        localState: null,
        network: {
            serverState: null,
            connectionState: ServerConnectionState.OFFLINE,
            specialMessage: null,
            nextID: 0,
            sentActions: [],
            pendingActions: [],
            goodbyeCode: 1000,
            goodbyeReason: "",
            autoReconnectAt: null,
            reconnectAttempts: null
        },
    };
    const [state, dispatch]: [AppState, Dispatch<AppAction>] = useReducer(appStateReducer, defaultState, undefined);

    const {user, map} = state.localState || {user: null, map: null}
    const offsets = useMemo(() => (!!map ? {
        top: 10,
        left: 10,
        size: 50,
        layout: map.layout
    } : null), [map])
    const mapElement = !!offsets && !!map ? <HexMapRenderer map={map} offsets={offsets} /> : null;
    const {width, height} = useMemo(() => !!offsets && !!map ? sizeFromLinesAndCells({
        bottomMargin: 10, cells: map.cellsPerLine, lines: map.lines, offsets: offsets, rightMargin: 10,
    }) : {width: 1, height: 1}, [map, offsets]);
    const colorPickerElement = !!user ? <HexColorPicker color={user?.activeColor} onChangeComplete={(colorResult) => dispatch({
        type: USER_ACTIVE_COLOR,
        color: colorResult.hex
    })} /> : null

  return (
    <div className="App">
        <DispatchContext.Provider value={dispatch}>
            <WebsocketReactAdapter url={"wss://hexmap.deliciousreya.net/map"} state={state.network.connectionState} specialMessage={state.network.specialMessage} pendingMessages={state.network.pendingActions} nextID={state.network.nextID} />
            <div className={"scrollBox"}>
                <div className={"centerBox"}>
                    <svg className={"map"} width={width} height={height} viewBox={`0 0 ${width} ${height}`} onContextMenu={(e) => e.preventDefault()}>
                        {mapElement}
                    </svg>
                </div>
            </div>
            {colorPickerElement}
        </DispatchContext.Provider>
    </div>
  );
}

export default App;
