// place files you want to import through the `$lib` alias in this folder.

import { majorAirportIATAs } from '$lib/icao';

interface ClientInfo {
	clientIp: string;
	clientLocation: string;
}

export async function getClientInfo(): Promise<ClientInfo> {
	let clientIp = 'Detecting...';
	let clientLocation = 'Detecting...';
	const res = await fetch('https://ipapi.co/json/');
	clientIp = 'Not available';
	clientLocation = 'Not available';
	if (res.ok) {
		const data = await res.json();
		clientIp = data.ip || 'Unknown';
		let location = '';
		if (data.city) location += data.city + ', ';
		if (data.region) location += data.region + ', ';
		if (data.country_name) location += data.country_name;
		clientLocation = location || 'Unknown';
	}
	return new Promise((resolve) =>
		resolve({
			clientIp,
			clientLocation
		})
	);
}

export async function sendAnalyticsData(bytesPerSecond: number, latency: number, location: string, progress: number) {
	// send measurements to analytics API
	const measurements = {
		bandwidth: bytesPerSecond,
		latency,
		location,
		progress
	};
	console.log('Sending analytics data');
	return new Promise((resolve) => {
		fetch('/analytics', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json'
			},
			body: JSON.stringify(measurements)
		})
			.then((response) => {
				if (!response.ok) {
					throw new Error(`Network response was not ok: ${response.status}`);
				}
				resolve(response);
			})
			.catch((error) => {
				console.error('Error sending bandwidth data:', error);
				resolve(null);
			});
	});
}

export async function getServerLocation(url: string): Promise<string> {
	// Get server location
	const response = await fetch(url, { method: 'HEAD' });
	let cdnPop = response.headers.get('x-amz-cf-pop');
	if (cdnPop !== null) {
		cdnPop = cdnPop.toUpperCase().slice(0, 3);
		// try to map to IATA
		if (cdnPop in majorAirportIATAs) {
			cdnPop = majorAirportIATAs[cdnPop].city + ', ' + majorAirportIATAs[cdnPop].country;
		} else {
			cdnPop = 'Unknown';
		}
	} else {
		cdnPop = 'Unknown';
	}

	return cdnPop;
}