import { useEffect, useReducer, useState } from 'react' import { Client, type ClientOptions, type GameFactoryInput, } from 'board-game-engine' import type { GameserverConnection } from './types' export type UseGameserverConnectionParams = Omit & { gameRules?: GameFactoryInput enabled?: boolean } export function useGameserverConnection ({ server, multiplayer, matchID, gameRules, gameName, boardgameIOGame, playerID, credentials, numPlayers, debug, enabled = true, }: UseGameserverConnectionParams): GameserverConnection | Record { const [_tick, forceUpdate] = useReducer((x: number) => x + 1, 0) const [connection, setConnection] = useState(null) useEffect(() => { if ( (!gameRules && !boardgameIOGame) || (credentials && !(matchID && enabled && server)) ) { return } const options: ClientOptions = { server, numPlayers, onClientUpdate: () => { forceUpdate() }, debug, matchID, gameRules, boardgameIOGame, gameName, playerID, credentials, multiplayer, } const newConnection = new Client(options) newConnection.connect() setConnection(newConnection) return () => { newConnection.client?.stop() setConnection(null) } }, [ matchID, server, playerID, credentials, gameRules, boardgameIOGame, enabled, multiplayer, ]) if (connection) { return Object.assign( connection, connection.getState?.(), ) as GameserverConnection } return {} }