//This function takes in latitude and longitude of two location and returns the distance between them as the crow flies (in km)
function CoordDistance(lat1: number, lon1: number, lat2: number, lon2: number) {
	const R = 6371; // km
	const dLat = toRad(lat2 - lat1);
	const dLon = toRad(lon2 - lon1);
	const lat1_calc = toRad(lat1);
	const lat2_calc = toRad(lat2);

	const a =
		Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		Math.sin(dLon / 2) *
			Math.sin(dLon / 2) *
			Math.cos(lat1_calc) *
			Math.cos(lat2_calc);
	const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	const d = R * c;
	return d;
}

// Converts numeric degrees to radians
function toRad(value: number) {
	return (value * Math.PI) / 180;
}

export function handleDistanceCoord(
	lat1: number,
	lon1: number,
	lat2: number,
	lon2: number,
) {
	const distance = CoordDistance(lat1, lon1, lat2, lon2);
	if (distance < 1) {
		return `~${Math.round(distance * 1000)} m`;
	}
	return `~${Math.round(distance)} km`;
}
