export const BASE = import.meta.env.DEV ? 'http://10.69.5.23' : '';

export type DataRow = Record<string, number | string | null>

const cache: any = {};

async function get<T>(path: string, params: Record<string, string> = {}): Promise<T> {
	const url = new URL(`${BASE}${path}`, window.location.origin);
	Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
	const key = url.toString();
	if(cache[key]) return cache[key];
	cache[key] = fetch(url.toString())
		.then(resp => resp.json())
		.finally(() => delete cache[key]);
	return cache[key];
}

export const api = {
	position: (fields?: string) => get<{latitude: number, longitude: number, altitude: number}>('/api/position', fields ? {fields} : {}),
	current: (fields?: string) => get<DataRow>('/api/current', fields ? {fields} : {}),
	hourly: (start?: Date, end?: Date, fields?: string) => get<DataRow[]>('/api/hourly', {
		...(start ? {start: start.toISOString().slice(0, 10)} : {}),
		...(end ? {end: end.toISOString().slice(0, 10)} : {}),
		...(fields ? {fields} : {})
	}),
	daily: (start?: Date, end?: Date, fields?: string) => get<DataRow[]>('/api/daily', {
		...(start ? {start: start.toISOString().slice(0, 10)} : {}),
		...(end ? {end: end.toISOString().slice(0, 10)} : {}),
		...(fields ? {fields} : {})
	}),
};
