import { useState } from 'react'

export type LocationInfo = {
	ip: string | null,
	country: string | null,
	region: string | null,
	city: string | null,
	latitude: string | null,
	longitude: string | null,
};

type ApiModel = {
	status: string | null,
	continent: string | null,
	country: string | null,
	regionName: string | null,
	city: string | null,
	district: string | null,
	zip: string | null,
	lat: string | null,
	lon: string | null,
	isp: string | null,
	query: string | null,
};

export default function useLocationInfo() {
	const [locationInfo, setLocationInfo] = useState<LocationInfo | null>(null);
	
	const getLocationInfo = async () =>{
		if (locationInfo != null){
			return locationInfo;
		}
		else{
			const response = await fetch("http://ip-api.com/json?fields=status,query,country,regionName,city,lat,lon")
			const model = await response.json() as ApiModel;
			const info = model == null || model.status == 'fail' ? null : {
				ip: model.query,
				country: model.country,
				region: model.regionName,
				city: model.city,
				latitude: model.lat,
				longitude: model.lon,
			} as LocationInfo
			setLocationInfo(info);
			return info;
		}
	}

	return { getLocationInfo };
}