import { useEffect } from 'react'; import { HealthcareService } from 'fhir/r4'; import { useWebSocketServiceContext } from '../services'; interface UseHealthcareServiceWebSocketOptions { healthcareService?: HealthcareService; healthcareServiceId?: string; isOpen?: boolean; onUpdate: (healthcareService: HealthcareService) => void; onDelete: () => void; } export const useFhirHealthcareServiceTargetedBroadcast = ({ healthcareService, healthcareServiceId, isOpen = true, onUpdate, onDelete }: UseHealthcareServiceWebSocketOptions) => { const { subscribe, unsubscribe } = useWebSocketServiceContext(); useEffect(() => { if (!healthcareService || !isOpen) { return; } const handleHealthcareServiceEvent = (cloudEvent: any) => { const healthcareServicePayload: HealthcareService = cloudEvent.data; const eventType = cloudEvent.type; const targetId = healthcareServiceId || healthcareService.id; if (healthcareServicePayload.id === targetId) { switch (eventType) { case 'com.akashichealthrecords.fhir.healthcareservice.updated': onUpdate(healthcareServicePayload); break; case 'com.akashichealthrecords.fhir.healthcareservice.deleted': onDelete(); break; } } }; subscribe('com.akashichealthrecords.fhir.healthcareservice.updated', handleHealthcareServiceEvent); subscribe('com.akashichealthrecords.fhir.healthcareservice.deleted', handleHealthcareServiceEvent); return () => { unsubscribe('com.akashichealthrecords.fhir.healthcareservice.updated', handleHealthcareServiceEvent); unsubscribe('com.akashichealthrecords.fhir.healthcareservice.deleted', handleHealthcareServiceEvent); }; }, [healthcareService, healthcareServiceId, isOpen, onUpdate, onDelete, subscribe, unsubscribe]); };