import { useEffect } from 'react'; import { Location } from 'fhir/r4'; import { useWebSocketServiceContext } from '../services'; interface UseLocationWebSocketOptions { location?: Location; locationId?: string; isOpen?: boolean; onUpdate: (location: Location) => void; onDelete: () => void; } export const useFhirLocationTargetedBroadcast = ({ location, locationId, isOpen = true, onUpdate, onDelete }: UseLocationWebSocketOptions) => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); useEffect(() => { if (!location || !isOpen) { return; } const handleLocationEvent = (cloudEvent: any) => { const locationPayload: Location = cloudEvent.data; const eventType = cloudEvent.type; const targetId = locationId || location.id; if (locationPayload.id === targetId) { switch (eventType) { case 'com.akashichealthrecords.fhir.location.updated': onUpdate(locationPayload); break; case 'com.akashichealthrecords.fhir.location.deleted': onDelete(); break; } } }; subscribe('com.akashichealthrecords.fhir.location.updated', handleLocationEvent); subscribe('com.akashichealthrecords.fhir.location.deleted', handleLocationEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.location.updated', handleLocationEvent); unsubscribe('com.akashichealthrecords.fhir.location.deleted', handleLocationEvent); }; }, [location, locationId, isOpen, onUpdate, onDelete, subscribe, unsubscribe]); };