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';

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 onConnectionDone = () => {
        setConnetionState("connected");
    };
    const onConnectionLost = () => {
        setConnetionState("reconnecting");
        connectToServer();
    };
    const onConnectionError = (event: Event) => {
        setConnetionState("error");
        connectToServer();
    };
    const onThemeChange = (theme: Theme) => {
        setTheme(theme)
    }
    const connectToServer = async () => {
        try {
            const userKey = await context.userKeyStore.getUserKey();
            setUserKey(userKey);
            (context.rtmt as RTMTWS).initWebSocket(userKey);
        } catch (error) {
            //TODO: check if it is network error!
            swal(context.texts.Error + "!", context.texts.ErrorWhenRetrievingInformation, "error");
            console.error(error);
        }
    };

    React.useEffect(() => {
        context.rtmt.on("open", onConnectionDone);
        context.rtmt.on("close", onConnectionLost);
        context.rtmt.on("error", onConnectionError);
        context.themeManager.on("themechange", onThemeChange);
        setConnetionState("connecting");
        connectToServer();
        return () => {
            context.rtmt.dispose();
            context.themeManager.off("themechange", onThemeChange);
        };
    }, []);

    const showConnectionState = connectionState != "connected";
    const floatingPanelColor = context.themeManager.theme.boardColor;
    const connectionStateText = () => {
        const map: { [key: string]: string } = {
            connecting: context.texts.Connecting,
            connected: context.texts.Connected,
            error: context.texts.CannotConnect,
            reconnecting: context.texts.ConnectingAgain,
        };
        return map[connectionState];
    };
    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={floatingPanelColor} visible={showConnectionState}>
                <span style={{ color: textColorOnBoard, transition: 'color 0.5s' }}>{connectionStateText()}</span>
            </FloatingPanel>
        </>
    );
}

export default MancalaApp;