import { getCollection } from "./collection.js" ; import { HassServices , HassDomainServices , UnsubscribeFunc } from "./types.js" ; import { Connection } from "./connection.js" ; import { Store } from "./store.js" ; import { getServices } from "./commands.js" ; import { debounce } from "./util.js" ; type ServiceRegisteredEvent = { data : { domain : string ; service : string ; } ; } ; type ServiceRemovedEvent = { data : { domain : string ; service : string ; } ; } ; function processServiceRegistered ( conn , store , event ) { const state = store . state ; if ( state === undefined ) return ; const { domain , service } = event . data ; if ( ! state . domain ?. service ) { const domainInfo = { ... state [ domain ] , [ service ] : { description : "" , fields : { } } , } ; store . setState ( { [ domain ] : domainInfo } ) ; } debouncedFetchServices ( conn , store ) ; } function processServiceRemoved ( state , event ) { if ( state === undefined ) return null ; const { domain , service } = event . data ; const curDomainInfo = state [ domain ] ; if ( ! curDomainInfo || ! ( service in curDomainInfo ) ) return null ; const domainInfo = { } ; Object . keys ( curDomainInfo ) . forEach ( ( sKey ) => { if ( sKey !== service ) domainInfo [ sKey ] = curDomainInfo [ sKey ] ; } ) ; return { [ domain ] : domainInfo } ; } const debouncedFetchServices = debounce ( ( conn , store ) => fetchServices ( conn ) . then ( ( services ) => store . setState ( services , true ) ) , 5000 ) ; const fetchServices = ( conn ) => getServices ( conn ) ; const subscribeUpdates = ( conn , store ) => Promise . all ( [ conn . subscribeEvents < ServiceRegisteredEvent > ( ( ev ) => processServiceRegistered ( conn , store , ev as ServiceRegisteredEvent ) , "service_registered" ) , conn . subscribeEvents < ServiceRemovedEvent > ( store . action ( processServiceRemoved ) , "service_removed" ) , ] ) . then ( ( unsubs ) => ( ) => unsubs . forEach ( ( fn ) => fn ( ) ) ) ; export const servicesColl = ( conn ) => getCollection ( conn , "_srv" , fetchServices , subscribeUpdates ) ; export const subscribeServices = ( conn , onChange ) : UnsubscribeFunc => servicesColl ( conn ) . subscribe ( onChange ) ;