import * as React from 'react';
import { FunctionComponent, useState } from 'react';
import {
    BrowserRouter,
    Routes,
    Route,
} from "react-router-dom";
import FloatingPanel from './components/FloatingPanel';
import GamePage from './routes/GamePage';
import Home from './routes/Home';

import { initContext } from './context/context';
import { RTMTWS } from './rtmt/rtmt_websocket';
import { getColorByBrightness } from './util/ColorUtil';
import { Theme } from './theme/Theme';
import LobyPage from './routes/LobyPage';
import swal from 'sweetalert';
import { ConnectionState } from './rtmt/rtmt';
import Util from './util/Util';

const context = initContext();

const MancalaApp: FunctionComponent = () => {

    const [userKey, setUserKey] = useState<string | undefined>(undefined);

    const [connectionState, setConnetionState] = useState<ConnectionState>("connecting");

    const [theme, setTheme] = useState<Theme>(context.themeManager.theme);

    const onConnectionError = (event: Event) => console.error("(RTMT) Connection Error: ", event);

    const onConnectionChange = (_connectionState: ConnectionState) => setConnetionState(_connectionState);

    const onThemeChange = (theme: Theme) => setTheme(theme);

    const connectRTMT = (userKey: string) => {
        const rtmt = context.rtmt as RTMTWS;
        rtmt.on("error", onConnectionError);
        rtmt.on("connectionchange", onConnectionChange)
        rtmt.connectWebSocket(userKey)
        return rtmt;
    }

    const loadUserKeyAndConnectServer = () => {
        context.userKeyStore.getUserKey().then((userKey: string) => {
            setUserKey(userKey);
            connectRTMT(userKey);
        }).catch((error) => {
            //TODO: check if it is network error!
            swal(context.texts.Error + "!", context.texts.ErrorWhenRetrievingInformation, "error");
            console.error(error);
        });
    }

    const disposeApp = () => {
        context.rtmt?.dispose();
        context.themeManager.off("themechange", onThemeChange);
    }

    React.useEffect(() => {
        loadUserKeyAndConnectServer();
        context.themeManager.on("themechange", onThemeChange);
        return () => disposeApp();
    }, []);

    const textColorOnBoard = getColorByBrightness(
        context.themeManager.theme.boardColor,
        context.themeManager.theme.textColor,
        context.themeManager.theme.textLightColor
    );
    return (
        <>
            <BrowserRouter>
                <Routes>
                    <Route index element={<Home context={context} theme={theme} userKey={userKey} />} />
                    <Route path="/" >
                        <Route path="game" >
                            <Route path=":gameId" element={<GamePage context={context} theme={theme} userKey={userKey} />}  ></Route>
                        </Route>
                        <Route path="loby" element={<LobyPage context={context} theme={theme} userKey={userKey} />}>
                        </Route>
                    </Route>
                </Routes>
            </BrowserRouter>
            <FloatingPanel context={context} color={context.themeManager.theme.boardColor} visible={connectionState != "connected"}>
                <span style={{ color: textColorOnBoard, transition: 'color 0.5s' }}>{Util.getTextByConnectionState(context, connectionState)}</span>
            </FloatingPanel>
        </>
    );
}

export default MancalaApp;