type Handler = (data: unknown) => void

let ws: WebSocket | null = null
let handler: Handler | null = null

function getUrl(): string {
  return `${window.location.origin.replace(/^http/, 'ws')}/ws`
}

export function connectSituationWebSocket(onData: Handler): () => void {
  handler = onData
  if (ws?.readyState === WebSocket.OPEN) return () => {}

  ws = new WebSocket(getUrl())
  ws.onmessage = (e) => {
    try {
      const msg = JSON.parse(e.data)
      if (msg.type === 'situation') handler?.({ situation: msg.data, stats: msg.stats })
    } catch (_) {}
  }
  ws.onclose = () => {
    ws = null
    setTimeout(() => handler && connectSituationWebSocket(handler), 3000)
  }
  return () => {
    handler = null
    ws?.close()
    ws = null
  }
}
