import { CommonMancalaGame, MancalaGame } from 'mancala.js';
import * as React from 'react';
import { FunctionComponent, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import Center from '../components/Center';
import CircularPanel from '../components/CircularPanel';
import HeaderBar from '../components/headerbar/HeaderBar';
import HeaderbarIcon from '../components/headerbar/HeaderbarIcon';
import HeaderbarTitle from '../components/headerbar/HeaderbarTitle';
import ThemeSwitchMenu from '../components/headerbar/ThemeSwitchMenu';
import PageContainer from '../components/PageContainer';
import Row from '../components/Row';
import { channel_on_game_start } from '../const/channel_names';
import { Context } from '../context/context';
import { Theme } from '../theme/Theme';
import { getColorByBrightness } from '../util/ColorUtil';

const LobyPage: FunctionComponent<{
    context: Context,
    userKey?: string,
    theme: Theme
}> = ({ context, userKey, theme }) => {

    let navigate = useNavigate();

    const onGameStart = (message: Object) => {
        const newGame: CommonMancalaGame = message as CommonMancalaGame;
        navigate(`/game/${newGame.id}`)
    }

    useEffect(() => {
        context.rtmt.addMessageListener(channel_on_game_start, onGameStart);
        context.rtmt.sendMessage("new_game", {});
        return () => {
            context.rtmt.removeMessageListener(channel_on_game_start, onGameStart);
        }
    }, []);
    
    const textColorOnAppBar = getColorByBrightness(
        context.themeManager.theme.appBarBgColor,
        context.themeManager.theme.textColor,
        context.themeManager.theme.textLightColor
    );
    const textColorOnBoard = getColorByBrightness(
        context.themeManager.theme.boardColor,
        context.themeManager.theme.textColor,
        context.themeManager.theme.textLightColor
    );
    return (
        <PageContainer theme={theme!}>
            <HeaderBar color={theme?.appBarBgColor}>
                <Row>
                    <Link style={{ textDecoration: 'none' }} to={"/"}>
                        <HeaderbarIcon />
                    </Link>
                    <Link style={{ textDecoration: 'none' }} to={"/"}>
                        <HeaderbarTitle title={context.texts.Mancala} color={textColorOnAppBar} />
                    </Link>
                </Row>
                <Row>
                    <ThemeSwitchMenu context={context} textColor={textColorOnAppBar} />
                </Row>
            </HeaderBar>
            <Center>
                <CircularPanel color={context.themeManager.theme.boardColor}>
                    <h4 style={{ margin: "0", color: textColorOnBoard }}>{`${context.texts.SearchingOpponent} ${context.texts.PleaseWait}...`}</h4>
                </CircularPanel>
            </Center>
        </PageContainer>
    );
}

export default LobyPage;