const geocodingApiBase: string = "https://geocoding-api.open-meteo.com/v1/search";
const openMeteoApiBase: string = "https://api.open-meteo.com/v1/forecast";
let location: string = "L'Hospitalet de Llobregat";
let previousLocation: string = '';

export async function load(): Promise<any> {
	let ubicacio: string = await getFromOpenMeteo(location).then( (res) => res.results[0].name );
	return { ubicacio }
};

function changeLocation(newLoc: string): void {
	previousLocation = location;
	location = newLoc;
}

function apiUrlBuilder(apiBaseUrl: string, vars: Array<[string, string | number]>): string {
	let jointVars: string[] = [];
	vars.forEach( (val) => jointVars.push(`${val[0]}=${val[1]}`) );
	let jointParams: string = jointVars.join('&');
	return `${apiBaseUrl}?${jointParams}`;
}

export const actions = {
	changeLoc: async ({ request }) => {
		const data: FormData = await request.formData();
		changeLocation(data.get('newloc'));
	}
}

async function getFromOpenMeteo(ubicacio: string): Promise<any> {
	let geoCodeResponse: Response = await fetch(`${geocodingApiBase}?name=${ubicacio}&count=1`);
	return geoCodeResponse.json();
}

async function getWeatherFromOpenMeteo(latitude: any, longitude: any) {
	let openMeteoResponse: Response = await fetch(apiUrlBuilder(openMeteoApiBase, [['latitude', latitude], ['longitude', longitude], ['hourly', 'temperature_2m,rain,showers,snowfall']]));
	return openMeteoResponse.json()
}
