import { useAuth } from '@/hooks/useAuth' import { useGame, useUpdateGameState, useUpdateMoney } from '@/hooks/useGame' import { useDownloadTrains } from '@/hooks/useTrain' import { isAuthValid } from '@/utils/features/auth/authSlice' import { useQuery } from '@tanstack/react-query' import { ReactNode, useEffect } from 'react' export default function GameProvider({ children }: { children: ReactNode }) { const auth = useAuth() const game = useGame() const updateGameState = useUpdateGameState() const updateMoney = useUpdateMoney() const downloadTrains = useDownloadTrains() const gameQuery = useQuery({ queryKey: ['get-game', auth.token], queryFn: () => fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/game/`, { headers: { "Authorization": `Bearer ${auth.token}` }} ).then(resp => resp.json()), enabled: isAuthValid(auth), refetchInterval: 5000, }) useEffect(() => { if (gameQuery.isSuccess && gameQuery.data) updateGameState(gameQuery.data) }, [gameQuery.status, gameQuery.dataUpdatedAt]) const playerQuery = useQuery({ queryKey: ['get-player', game.playerId, auth.token], queryFn: () => fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/players/${game.playerId}/`, { headers: { "Authorization": `Bearer ${auth.token}` }} ).then(resp => resp.json()), enabled: isAuthValid(auth) && !!game.playerId, refetchInterval: 5000, }) useEffect(() => { if (playerQuery.isSuccess && playerQuery.data) updateMoney(playerQuery.data.money) }, [playerQuery.status, playerQuery.dataUpdatedAt]) const trainsQuery = useQuery({ queryKey: ['get-trains', game.playerId, auth.token], queryFn: () => fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/trains/?playerId=${game.playerId}&size=10000`, { headers: { "Authorization": `Bearer ${auth.token}` }} ).then(resp => resp.json()), enabled: isAuthValid(auth) && !!game.playerId, refetchInterval: 5000, }) useEffect(() => { if (trainsQuery.isSuccess && trainsQuery.data && trainsQuery) downloadTrains(trainsQuery.data) }, [trainsQuery.status, trainsQuery.dataUpdatedAt]) return <> {children} }