async function refresh_overview(server_address) {
	const response = await fetch_api(server_address, "overview");
	if (response.data) {
		return response.data;
	} else {
		if (response.error) {
			return response.error;
		} else {
			return null;
		}
	}
}

async function refresh_hints(server_address) {
	const response = await fetch_api(server_address, "hints");
	if (response.data) {
		return response.data;
	} else {
		return null;
	}
}

async function refresh_checks(server_address) {
	const response = await fetch_api(server_address, "items");
	if (response.data) {
		return response.data;
	} else {
		return null;
	}
}

async function refresh_entrances(server_address) {
	const response = await fetch_api(server_address, "doors");
	if (response.data) {
		return response.data;
	} else {
		return null;
	}
}

async function fetch_api(server_address, uri) {
	try {
		const response = await fetch(`${server_address}${uri}`, {
			signal: AbortSignal.timeout(1100),
		});
		if (response.ok) {
			const data = await response.json();
			if (!("error" in data)) {
				return { data: data, error: null };
			} else {
				return { data: null, error: data };
			}
		} else {
			return { data: null, error: null };
		}
	} catch (e) {
		return { data: null, error: e };
	}
}

AbortSignal.timeout ??= function timeout(ms) {
	const ctrl = new AbortController();
	setTimeout(() => ctrl.abort(), ms);
	return ctrl.signal;
};

export default {
	refresh_overview,
	refresh_checks,
	refresh_entrances,
	refresh_hints,
	fetch_api,
};
