"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);
		});
		source.addEventListener("update", (message) => {
			const updatedSchedule: Schedule = JSON.parse(message.data);
			console.log("Update", updatedSchedule);
			setSchedule(updatedSchedule);
		});
		return () => {
			console.log("Closing event source")
			source.close();
		}
	}, [])
	return (
		<ScheduleContext.Provider value={schedule}>
			{props.children}
		</ScheduleContext.Provider>
	);
}

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