import { ReactNode, useEffect } from 'react' import { useAuth } from '@/hooks/useAuth' import { useQueuedLocations, useSetLastPlayerLocation, useSetLastPlayerLocations, useUnqueueLocation } from '@/hooks/useLocation' import { useGeolocationMutation } from '@/hooks/mutations/useGeolocationMutation' import { useStartGeolocationServiceEffect } from '@/utils/geolocation' import { Platform } from 'react-native' import { useQuery } from '@tanstack/react-query' import { isAuthValid } from '@/utils/features/auth/authSlice' import { socket } from '@/utils/socket' import { PlayerLocation } from '@/utils/features/location/locationSlice' import { Constants } from '@/constants/Constants' export default function GeolocationProvider({ children }: { children: ReactNode }) { useStartGeolocationServiceEffect() const auth = useAuth() const geolocationsQueue = useQueuedLocations() const unqueueLocation = useUnqueueLocation() const setLastPlayerLocations = useSetLastPlayerLocations() const setLastPlayerLocation = useSetLastPlayerLocation() const geolocationMutation = useGeolocationMutation({ auth, onPostSuccess: (data, variables) => unqueueLocation(variables), onError: ({ response, error }) => console.error(response, error), }) if (Platform.OS !== "web") { useEffect(() => { if (geolocationsQueue.length === 0 || geolocationMutation.isPending || !isAuthValid(auth)) return const locToSend = geolocationsQueue[0] geolocationMutation.mutate(locToSend) }, [auth, geolocationMutation.status, geolocationsQueue]) } const lastLocationsQuery = useQuery({ queryKey: ['get-last-locations', auth.token], queryFn: () => fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/geolocations/last-locations/`, { method: "GET", headers: { "Authorization": `Bearer ${auth.token}`, "Content-Type": "application/json", }, }).then(resp => resp.json()), initialData: [], enabled: isAuthValid(auth), refetchInterval: Constants.QUERY_REFETCH_INTERVAL * 1000, }) useEffect(() => { if (lastLocationsQuery.isSuccess && lastLocationsQuery.data) setLastPlayerLocations(lastLocationsQuery.data) }, [lastLocationsQuery.status, lastLocationsQuery.dataUpdatedAt]) socket.on('last-location', (data: PlayerLocation) => { if (data.playerId) setLastPlayerLocation(data) }) return <> {children} }