import type { Socket } from 'socket.io-client'
import { createSharedComposable } from '@vueuse/core'
import { io } from 'socket.io-client'

export const useSignaling = createSharedComposable(() => {
  const toast = useToast()

  const socket = shallowRef<Socket>()

  const connected = ref(false)

  watch(socket, (socket, prevSocket) => {
    if (prevSocket) {
      prevSocket.close()
    }

    if (!socket) {
      return
    }

    if (import.meta.dev) {
      socket.onAny((event, ...args) => {
        console.info('[onAny]', event, args)
      })

      socket.onAnyOutgoing((event, ...args) => {
        console.info('[onAnyOutgoing]', event, args)
      })
    }

    socket.on('connect', async () => {
      connected.value = true
    })

    socket.on('disconnect', async () => {
      connected.value = false
    })
  }, { immediate: true, flush: 'sync' })

  watch(connected, (connected) => {
    if (connected)
      toast.add({ severity: 'success', summary: 'Connected', closable: false, life: 1000 })
    else
      toast.add({ severity: 'error', summary: 'Disconnected', closable: false, life: 1000 })
  }, { immediate: true })

  onScopeDispose(() => {
    socket.value?.close()
  })

  function connect() {
    if (socket.value)
      return

    socket.value = io('https://api.koptilnya.xyz/webrtc', {
      // socket.value = io('http://127.0.0.1:4000/webrtc', {
      path: '/chad/ws',
      transports: ['websocket'],
    })
  }

  return {
    socket,
    connected,
    connect,
  }
})
