import { useEffect } from 'react'; import { DocumentReference } from 'fhir/r4'; import { usePatientServiceContext, useWebSocketServiceContext } from '../services'; interface UseDocumentReferenceWebSocketOptions { documentReference?: DocumentReference; documentReferenceId?: string; isRoot?: boolean isOpen?: boolean; onUpdate: (documentReference: DocumentReference) => void; onDelete: () => void; } export const useFhirDocumentReferenceTargetedBroadcast = ({ documentReference, documentReferenceId, isRoot = false, isOpen = true, onUpdate, onDelete }: UseDocumentReferenceWebSocketOptions) => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { patientState } = usePatientServiceContext(); useEffect(() => { if ((!patientState && !isRoot) || !documentReference || !isOpen) { return; } const handleDocumentReferenceEvent = (cloudEvent: any) => { const documentReferencePayload: DocumentReference = cloudEvent.data; const eventType = cloudEvent.type; const targetId = documentReferenceId || documentReference.id; if (documentReferencePayload.id === targetId) { switch (eventType) { case 'com.akashichealthrecords.fhir.documentreference.updated': onUpdate(documentReferencePayload); break; case 'com.akashichealthrecords.fhir.documentreference.deleted': onDelete(); break; } } }; subscribe('com.akashichealthrecords.fhir.documentreference.updated', handleDocumentReferenceEvent); subscribe('com.akashichealthrecords.fhir.documentreference.deleted', handleDocumentReferenceEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.documentreference.updated', handleDocumentReferenceEvent); unsubscribe('com.akashichealthrecords.fhir.documentreference.deleted', handleDocumentReferenceEvent); }; }, [patientState, documentReference, documentReferenceId, isOpen, onUpdate, onDelete, subscribe, unsubscribe]); };