import { CommonMancalaGame } from 'mancala.js'; import * as React from 'react'; import { FunctionComponent, useEffect, useState } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; import AppHeader from '../components/headerbar/AppHeader'; import PageContainer from '../components/PageContainer'; import { BOT_OFFER_DELAY_MS, BotLevel, channel_cancel_new_game, channel_new_bot_game, channel_new_game, channel_on_game_start, channel_on_new_game_rejected, isBotLevel } from '@mancala/core'; import BotLevelPicker from '../components/BotLevelPicker'; import { Context } from '../context/context'; import { Theme } from '@mancala/core'; import { useTranslation } from 'react-i18next'; const LobyPage: FunctionComponent<{ context: Context, userKey?: string, theme: Theme }> = ({ context }) => { let navigate = useNavigate(); const { t } = useTranslation(); // /loby?bot= starts a game against the bot at once instead of searching for an opponent. const [searchParams] = useSearchParams(); const botParam = searchParams.get("bot"); const botLevel: BotLevel | undefined = isBotLevel(botParam) ? botParam : undefined; // Set when the server refuses a new game because the user has one in progress. const [activeGameId, setActiveGameId] = useState(undefined); // Shown when no opponent has been found for a while. const [botOffered, setBotOffered] = useState(false); const onNewGameRejected = (message: { gameId: string }) => setActiveGameId(message.gameId); const onGameStart = (message: Object) => { const newGame: CommonMancalaGame = message as CommonMancalaGame; navigate(`/game/${newGame.id}`) } const startBotGame = (level: BotLevel) => { context.rtmt.sendMessage(channel_new_bot_game, { level }); } const onCancelNewGameClick = () => { if (context.rtmt.connectionState === "connected") { context.rtmt.sendMessage(channel_cancel_new_game, ""); } navigate("/") } useEffect(() => { context.rtmt.addMessageListener(channel_on_game_start, onGameStart); context.rtmt.addMessageListener(channel_on_new_game_rejected, onNewGameRejected); let botOfferTimer: ReturnType | undefined; if (botLevel) { startBotGame(botLevel); } else { context.rtmt.sendMessage(channel_new_game, {}); botOfferTimer = setTimeout(() => setBotOffered(true), BOT_OFFER_DELAY_MS); } return () => { if (botOfferTimer) clearTimeout(botOfferTimer); context.rtmt.removeMessageListener(channel_on_game_start, onGameStart); context.rtmt.removeMessageListener(channel_on_new_game_rejected, onNewGameRejected); } }, []); return (
{!activeGameId && }

{activeGameId ? t("GameInProgress") : botLevel ? t("PlayWithBot") : t("SearchingOpponent")}

{!activeGameId &&

{`${t("PleaseWait")}...`}

} {!activeGameId && botOffered && (

{t("NoOpponentYet")}

)}
{activeGameId && ( )}
); } export default LobyPage;