<template>
	<main>
		<h1>Schedule & Events</h1>
		<p>
			Study carefully, we only hold these events once a year.
		</p>
		<p v-if="!session">
			<NuxtLink to="/login">Login</NuxtLink> or <NuxtLink to="/login#create-account">Create an account</NuxtLink>
			to get notified about updates to the schedule.
		</p>
		<p v-else>
			Check out your <NuxtLink to="/account/settings">Account Setting</NuxtLink> to set up notifications for changes to schedule.
		</p>
		<h2>Schedule</h2>
		<Timetable />
		<EventsEdit />
		<h2>Events</h2>
		<EventCard v-for="event in schedule.events" :event/>
		<h2>Locations</h2>
		<ul>
			<li v-for="location in schedule.locations" :key="location.id">
				<h3>{{ location.name }}</h3>
				{{ location.description ?? "No description provided" }}
			</li>
		</ul>
	</main>
</template>

<script setup lang="ts">
import type { Schedule } from '~/shared/types/schedule';
const { data: session } = await useAccountSession();

const schedule = useSchedule();

await callOnce(async () => {
	schedule.value = await $fetch("/api/schedule");
})

const source = ref<EventSource | null>(null);

onMounted(() => {
	console.log("Opening event source")
	source.value = new EventSource("/api/events");
	source.value.addEventListener("message", (message) => {
		console.log("Message", message.data);
	});
	source.value.addEventListener("update", (message) => {
		const updatedSchedule: Schedule = JSON.parse(message.data);
		console.log("Update", updatedSchedule);
		schedule.value = updatedSchedule;
	});
})

onUnmounted(() => {
	if (source.value) {
		console.log("Closing event source")
		source.value.close();
		source.value = null;
	}
});
</script>
