import type { ChadClient } from '#shared/types'
import { useLocalStorage } from '@vueuse/core'

export function useClient(socketId: MaybeRef<ChadClient['socketId']>) {
  const mediasoup = useMediasoup()
  const { getClient } = useClients()

  const client = computed(() => getClient(unref(socketId))!)

  const volume = useLocalStorage<number>(computed(() => `CLIENT_VOLUME_${client.value.userId}`), 100, { writeDefaults: false })
  const premuted = useLocalStorage<boolean>(computed(() => `CLIENT_PREMUTED_${client.value.userId}`), false, { writeDefaults: false })

  const consumers = computed(() => {
    return Object.values(mediasoup.consumers.value).filter(consumer => consumer.appData.socketId === client.value.socketId)
  })

  const audioConsumers = computed(() => {
    return mediasoup.audioConsumers.value.filter(consumer => consumer.appData.socketId === client.value.socketId)
  })

  const videoConsumers = computed(() => {
    return mediasoup.videoConsumers.value.filter(consumer => consumer.appData.socketId === client.value.socketId)
  })

  const shareConsumers = computed(() => {
    return mediasoup.shareConsumers.value.filter(consumer => consumer.appData.socketId === client.value.socketId)
  })

  const producers = computed(() => {
    return Object.values(mediasoup.producers.value).filter(producer => producer.appData.socketId === client.value.socketId)
  })

  const streaming = computed(() => {
    return videoConsumers.value.length > 0 || shareConsumers.value.length > 0
  })

  const speaking = computed(() => {
    return mediasoup.speakingClients.value.some(speaker => speaker.clientId === client.value.socketId)
  })

  return {
    volume,
    premuted,
    consumers,
    producers,
    audioConsumers,
    videoConsumers,
    shareConsumers,
    streaming,
    speaking,
  }
}
