import { useEffect, useRef } from 'react'; import { useOptionalWebSocketServiceContext } from '../services/WebSocketService'; import { DAY_EVENT_TYPES, readDayEvent, type DayEvent } from '../utils/liveDayEvents'; /** * Feeds appointment and encounter broadcasts to a day board, and asks for one read when the socket comes * back, since events sent while it was down are gone. Subscribes once; the handlers are read through refs. * Without a socket provider it does nothing and the board keeps its fallback read. */ export const useLiveDayEvents = (onEvent: (event: DayEvent) => void, onReconnect: () => void): void => { const socket = useOptionalWebSocketServiceContext(); const subscribe = socket?.subscribe; const unsubscribe = socket?.unsubscribe; const isConnected = socket?.isConnected ?? false; const handlers = useRef({ onEvent, onReconnect }); handlers.current = { onEvent, onReconnect }; useEffect(() => { if (!subscribe || !unsubscribe) return undefined; const listener = (cloudEvent: { type?: string; data?: unknown }) => { const event = readDayEvent(cloudEvent); if (event) handlers.current.onEvent(event); }; DAY_EVENT_TYPES.forEach((type) => subscribe(type, listener)); return () => DAY_EVENT_TYPES.forEach((type) => unsubscribe(type, listener)); }, [subscribe, unsubscribe]); const connectedBefore = useRef(false); const previous = useRef(isConnected); useEffect(() => { if (isConnected && !previous.current && connectedBefore.current) handlers.current.onReconnect(); if (isConnected) connectedBefore.current = true; previous.current = isConnected; }, [isConnected]); };