import { createGlobalState } from '@vueuse/core'
import { useClients } from '~/composables/use-clients'

export const useApp = createGlobalState(() => {
  const { clients } = useClients()
  const mediasoup = useMediasoup()
  const toast = useToast()

  const inputMuted = ref(false)
  const outputMuted = ref(false)

  const previousInputMuted = ref(inputMuted.value)

  const me = computed(() => clients.value.find(client => client.isMe))

  function muteInput() {
    inputMuted.value = true
  }

  function unmuteInput() {
    inputMuted.value = false
  }

  function toggleInput() {
    if (inputMuted.value)
      unmuteInput()
    else
      muteInput()
  }

  function muteOutput() {
    outputMuted.value = true
  }

  function unmuteOutput() {
    outputMuted.value = false
  }

  function toggleOutput() {
    if (outputMuted.value)
      unmuteOutput()
    else
      muteOutput()
  }

  watch(inputMuted, async (inputMuted) => {
    if (inputMuted) {
      await mediasoup.muteMic()
    }
    else {
      if (outputMuted.value) {
        outputMuted.value = false
      }
      await mediasoup.unmuteMic()
    }

    const toastText = inputMuted ? 'Microphone muted' : 'Microphone activated'
    toast.add({ severity: 'info', summary: toastText, closable: false, life: 1000 })
  })

  watch(outputMuted, (outputMuted) => {
    if (outputMuted) {
      previousInputMuted.value = inputMuted.value
      muteInput()
    }
    else {
      inputMuted.value = previousInputMuted.value
    }

    const toastText = outputMuted ? 'Sound muted' : 'Sound resumed'
    toast.add({ severity: 'info', summary: toastText, closable: false, life: 1000 })
  })

  return {
    clients,
    me,
    inputMuted,
    muteInput,
    unmuteInput,
    toggleInput,
    outputMuted,
    muteOutput,
    unmuteOutput,
    toggleOutput,
  }
})
