"use client";
import { createContext, useContext, useEffect, useState } from "react";
import { Schedule } from "./types";

const ScheduleContext = createContext<Schedule | null>(null);

interface ScheduleProviderProps {
	children: React.ReactElement;
	schedule: Schedule;
}

export function ScheduleProvider(props: ScheduleProviderProps) {
	const [schedule, setSchedule] = useState(props.schedule);
	useEffect(() => {
		console.log("Opening event source")
		const source = new EventSource("/api/events");
		source.addEventListener("message", (message) => {
			console.log("Message", message.data);
			setSchedule(old => {
				const copy: Schedule = JSON.parse(JSON.stringify(old));
				const ts = copy.events[0].slots[0].start;
				copy.events[0].slots[0].start = new Date(Date.parse(ts) + 36e5).toISOString();
				return copy;
			})
		});
		source.addEventListener("update", (message) => console.log("Update", message.data));
		return () => {
			console.log("Closing event source")
			source.close();
		}
	}, [])
	return (
		<ScheduleContext.Provider value={schedule}>
			{props.children}
		</ScheduleContext.Provider>
	);
}

export function useSchedule() {
	return useContext(ScheduleContext);
}
