export type Coordinates = {
    latitude: number
    longitude: number
}

function geolocation_to_simple_coords(coordinates: GeolocationCoordinates): Coordinates {
    return { latitude: coordinates.latitude, longitude: coordinates.longitude }
}

export function get_coords(): Promise<{ coords: Coordinates | null; error: string | null }> {
    return new Promise((resolve) => {
        if (!navigator.geolocation) {
            resolve({ coords: null, error: "Geolocation is not supported by your browser" })
            return
        }

        const error_callback = (gps_error: GeolocationPositionError) => {
            console.log(gps_error)
            resolve({
                coords: null,
                error: `Unable to retrieve your location: (${gps_error.message})`,
            })
            return
        }

        const success_callback = (gps_position: GeolocationPosition) => {
            resolve({
                coords: geolocation_to_simple_coords(gps_position.coords),
                error: null,
            })
            return
        }

        navigator.geolocation.getCurrentPosition(success_callback, error_callback)
    })
}
