import { ReactNode, useEffect } from 'react'
import { useAuth } from '@/hooks/useAuth'
import { useQueuedLocations, useUnqueueLocation } from '@/hooks/useLocation'
import { useGeolocationMutation } from '@/hooks/mutations/useGeolocationMutation'
import { useStartGeolocationServiceEffect } from '@/utils/geolocation'

export default function GeolocationProvider({ children }: { children: ReactNode }) {
  useStartGeolocationServiceEffect()

  const auth = useAuth()
  const geolocationsQueue = useQueuedLocations()
  const unqueueLocation = useUnqueueLocation()
  const geolocationMutation = useGeolocationMutation({
    auth,
    onPostSuccess: ({ data, variables: location }) => {
      unqueueLocation(location)
      geolocationMutation.reset()
    },
    onError: ({ response, error }) => { console.error(response, error) }
  })
  
    useEffect(() => {
    if (geolocationsQueue.length === 0 || geolocationMutation.isPending)
      return
    const locToSend = geolocationsQueue[0]
    geolocationMutation.mutate(locToSend)
  }, [auth, geolocationsQueue])

  return <>
    {children}
  </>
}