import { onCleanup , onMount , createMemo } from 'solid-js' ; import { DeviceData , GenericObject } from '../../../@types/alltypes' ; import { useStore } from '..' ; import { subscribe , emit } from '../../lib/socket' ; import { initialState } from '../state/_app' ; export const useDevices = ( ) => { const [ { user : user , app : app } , setState ] = useStore ( ) ; const connectLocalDevice = ( ) => { const { appCodeName : deviceName } = navigator ; emit ( 'device:add' , { deviceId : app . deviceId , deviceName } ) ; } ; const subscribeToDevicesSync = ( ) => subscribe ( 'devices:sync' , ( devices ) => setState ( 'app' , { devices } ) ) ; const setMasterDevice = ( deviceId ) => { const { deviceId : masterDeviceId } = app . devices . find ( ( { isMaster } ) => isMaster ) || { } ; if ( deviceId !== masterDeviceId ) { emit ( 'device:active' , deviceId ) ; } } ; const synchronizePlayer = ( data ) => emit ( 'player:sync' , data ) ; const subscribeToPlayerSync = ( callback ) => subscribe ( 'player:sync' , callback ) ; const currentDevice = createMemo ( ( ) => app . devices . find ( ( { deviceId : id } ) => id === app . deviceId ) || { isMaster : true } , app . deviceId ) ; const availableDevices = createMemo ( ( ) => app . devices . filter ( ( { deviceId : id } ) => id !== app . deviceId ) , app . deviceId ) ; onMount ( ( ) => { subscribe ( 'connect' , ( ) => { emit ( 'room' , user . id ) ; connectLocalDevice ( ) ; subscribeToDevicesSync ( ) ; } ) ; subscribe ( 'disconnect' , ( ) => setState ( 'app' , { devices : initialState ( ) . devices } ) ) ; } ) ; onCleanup ( ( ) => emit ( 'device:delete' , app . deviceId ) ) ; return { currentDevice , availableDevices , setMasterDevice , synchronizePlayer , subscribeToPlayerSync } ; } ;