import { eventBus } from "../services/eventEmitter.js";
import "../services/index.js";
import { useStudio } from "./StudioProvider.js";
import { useMe } from "../hooks/useAuth.js";
import { c } from "react/compiler-runtime";
import { useEffect, useRef } from "react";
function SseProvider() {
	let s = c(5), { environment: l } = useStudio(), { data: u, isSuccess: d } = useMe(), f = useRef(null), p, m;
	return s[0] !== l.url || s[1] !== d || s[2] !== u ? (p = () => {
		if (l.url && d && u) {
			f.current &&= (f.current.close(), null);
			let a = `${l.url}/api/v1/sse/stream`, o = new EventSource(a, { withCredentials: !0 });
			return f.current = o, o.onopen = _temp, o.onerror = () => {
				o.readyState === EventSource.CLOSED && console.warn("SSE connection closed. Refresh the page if it does not recover.");
			}, [
				"workflow.created",
				"workflow.updated",
				"document.created",
				"pipeline.updated",
				"workspace.updated"
			].forEach((a) => {
				o.addEventListener(a, (o) => {
					try {
						let a = JSON.parse(o.data);
						eventBus.emit(a.type, a);
					} catch (e) {
						let o = e;
						console.error(`Error parsing SSE event [${a}]:`, o);
					}
				});
			}), () => {
				o.close(), f.current = null;
			};
		}
	}, m = [
		l.url,
		d,
		u
	], s[0] = l.url, s[1] = d, s[2] = u, s[3] = p, s[4] = m) : (p = s[3], m = s[4]), useEffect(p, m), null;
}
function _temp() {
	console.log("SSE connection established");
}
export { SseProvider };
