// WebSocket over the host bridge. Same event surface as the browser's (open/message/close/error)
// via the shared Emitter. Ported from worker/src/WebSocket.ts.

import { Emitter } from "../core/events"

type SocketEvents = {
  open: () => void
  message: (data: any) => void
  close: (code?: number) => void
  error: () => void
}

export class WebSocket extends Emitter<SocketEvents> {
  private _id: number | null = null

  constructor(url: string, headers?: Record<string, string>) {
    super()
    this._id = _creatorUtils.websocketOpen(url, (channel, data) => this._onMessage(channel, data), headers)
  }

  send(message: string | ArrayBuffer): void {
    if (this._id !== null) _creatorUtils.websocketSend(this._id, message)
  }

  close(): void {
    if (this._id !== null) {
      _creatorUtils.websocketClose(this._id)
      this._id = null
    }
  }

  private _onMessage(channel: string, data: any): void {
    if (data !== undefined && data !== null) this.dispatch(channel as keyof SocketEvents, data)
    else this.dispatch(channel as keyof SocketEvents)
  }
}
