import { useEffect } from 'react'; import { MedicationStatement } from 'fhir/r4'; import { useMedicationStatementServiceContext, usePatientServiceContext, useWebSocketServiceContext } from '../services'; import { refersToPatient } from '../utils/writeThroughHold'; interface UseMedicationStatementWebSocketOptions { medicationStatement?: MedicationStatement; medicationStatementId?: string; isOpen?: boolean; onUpdate: (medicationStatement: MedicationStatement) => void; onDelete: () => void; } export const useFhirMedicationStatementTargetedBroadcast = ({ medicationStatement, medicationStatementId, isOpen = true, onUpdate, onDelete }: UseMedicationStatementWebSocketOptions) => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); const { patientState } = usePatientServiceContext(); // Admitted by the service's per-record floor, as the list is: an older, unordered or removed copy never reaches it. const { admitMedicationEvent } = useMedicationStatementServiceContext(); useEffect(() => { if (!patientState || !medicationStatement || !isOpen) { return; } const handleMedicationStatementEvent = (cloudEvent: any) => { const medicationStatementPayload: MedicationStatement = cloudEvent.data; const eventType = cloudEvent.type; const targetId = medicationStatementId || medicationStatement.id; // The same id about another patient is not this medication. if (medicationStatementPayload.id === targetId && refersToPatient(medicationStatementPayload, patientState.id)) { switch (eventType) { case 'com.akashichealthrecords.fhir.medicationstatement.updated': if (admitMedicationEvent(medicationStatementPayload, 'updated')) onUpdate(medicationStatementPayload); break; case 'com.akashichealthrecords.fhir.medicationstatement.deleted': admitMedicationEvent(medicationStatementPayload, 'deleted'); onDelete(); break; } } }; subscribe('com.akashichealthrecords.fhir.medicationstatement.updated', handleMedicationStatementEvent); subscribe('com.akashichealthrecords.fhir.medicationstatement.deleted', handleMedicationStatementEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.medicationstatement.updated', handleMedicationStatementEvent); unsubscribe('com.akashichealthrecords.fhir.medicationstatement.deleted', handleMedicationStatementEvent); }; }, [patientState, medicationStatement, medicationStatementId, isOpen, onUpdate, onDelete, subscribe, unsubscribe, admitMedicationEvent]); };