// Network client for WebSocket communication / WebSocket 通信网络客户端
import { MSG_TYPE } from '../utils/constants.js'

/**
 * WebSocket client that handles connection and message routing / WebSocket 客户端，处理连接和消息路由
 */
export class NetworkClient {
  constructor() {
    this.ws = null
    this.connected = false
    // Message handlers by type / 按类型存储的消息处理器
    this.handlers = new Map()
  }

  // Connect to WebSocket server / 连接 WebSocket 服务器
  async connect(url) {
    return new Promise((resolve, reject) => {
      this.ws = new WebSocket(url)

      this.ws.onopen = () => {
        this.connected = true
        resolve()
      }

      this.ws.onerror = (e) => {
        reject(e)
      }

      this.ws.onclose = () => {
        this.connected = false
      }

      this.ws.onmessage = (e) => {
        try {
          const msg = JSON.parse(e.data)
          const handlers = this.handlers.get(msg.type)
          if (handlers) {
            for (const h of handlers) {
              h(msg.data || {})
            }
          }
        } catch (err) {
          console.error('Failed to parse message:', err)
        }
      }
    })
  }

  // Disconnect from server / 断开服务器连接
  disconnect() {
    if (this.ws) {
      this.ws.close()
      this.ws = null
      this.connected = false
    }
  }

  // Register a message handler for a specific type / 为特定类型注册消息处理器
  on(type, handler) {
    if (!this.handlers.has(type)) {
      this.handlers.set(type, [])
    }
    this.handlers.get(type).push(handler)
  }

  // Send a message to the server / 向服务器发送消息
  send(type, data = {}) {
    if (this.ws && this.connected) {
      this.ws.send(JSON.stringify({ type, data }))
    }
  }

  // Create a new room / 创建新房间
  createRoom(playerName) {
    this.send(MSG_TYPE.CREATE_ROOM, { playerName })
  }

  // Join an existing room / 加入已有房间
  joinRoom(roomId, playerName) {
    this.send(MSG_TYPE.JOIN_ROOM, { roomId, playerName })
  }

  // Leave current room / 离开当前房间
  leaveRoom() {
    this.send(MSG_TYPE.LEAVE_ROOM)
  }

  // Request room list / 请求房间列表
  requestRoomList() {
    this.send(MSG_TYPE.ROOM_LIST)
  }

  // Signal ready state / 发送准备状态
  ready() {
    this.send(MSG_TYPE.READY)
  }

  // Start the game (host only) / 开始游戏（仅房主）
  startGame() {
    this.send(MSG_TYPE.START_GAME)
  }

  // Send player input to server / 向服务器发送玩家输入
  sendInput(inputState) {
    this.send(MSG_TYPE.PLAYER_INPUT, inputState)
  }
}
