import user, { UserRole } from '~/store/user';

export type TSocketRes<T> = {
  content: T
  from_client_id: string
  from_client_name: string
  time: string
  to_client_id: string
  type: string
}

const CLIENT_NAME = `${user.user_id}|${user.user_realname}|${UserRole}`
export function createSocket(
  options: { teacher: string, student: string },
  hooks: {
    message: Function
  }
) {
  const ws = new WebSocket("wss://socket.bozedu.net")

  ws.addEventListener('message', (e) => {
    if (e.data) {
      try {
        const data: TSocketRes<string> = JSON.parse(e.data)
        if (CLIENT_NAME === data.from_client_name) return
        if (data.type !== 'ping') {
          console.groupCollapsed(`Socket : ${data.type}`)
          console.log(data);
          console.groupEnd();
        }

        if (data.type === 'login') {

        }

        if (data.type === 'say') {
          const content = {
            ...data,
            content: JSON.parse(decodeURIComponent(data.content))
          }
          console.groupCollapsed(`├─ Socket Say:`)
          console.log(content);
          console.groupEnd();

          hooks.message(content)
        }
      } catch (error) {
        console.error(error);
      }
    }
  })

  ws.addEventListener('error', (err) => {
    console.error('ws error :>> ', ws, err);
  })

  ws.addEventListener('open', (e) => {
    ws.send(JSON.stringify({
      "type": "login",
      "client_name": CLIENT_NAME,
      "room_id": `aiwen_consult_${options.teacher}_${options.student}`
    }))
  })


  return ws
}

export function socketSend(ws: WebSocket, content: unknown) {
  ws.send(
    JSON.stringify({
      type: "say",
      to_client_id: 'all',
      content: encodeURIComponent(JSON.stringify(content))
    })
  )
}
