export class LiveWS {
  /**
   * @param {string} url - WebSocket 服务器地址
   * @param {number} liveId - 直播间ID
   * @param {number} userId - 用户ID
   * @param {number} checkInterval - 检查连接状态的时间间隔，单位毫秒
   * @param {number} reconnectDelay - 连接断开后重连的延迟，单位毫秒
   */
  constructor(url, liveId, userId, checkInterval = 5000, reconnectDelay = 3000) {
    this.url = url + `?liveId=${liveId}&userId=${userId}`;
    this.liveId = liveId;
    this.userId = userId;
    this.checkInterval = checkInterval;
    this.reconnectDelay = reconnectDelay;
    this.ws = null;
    this.isManualClose = false;
    this.connect();
    this.startHeartbeat();
  }

  connect() {
    console.log("Connecting to WebSocket:");
    this.ws = new WebSocket(this.url);

    // 绑定事件
    this.ws.onopen = (event) => {
      console.log("WebSocket connected:", event);
    };

    this.ws.onmessage = (event) => {
      console.log("Received message:", event.data);
      // 根据需要处理消息
    };

    this.ws.onerror = (error) => {
      console.error("WebSocket error:", error);
    };

    this.ws.onclose = (event) => {
      console.warn("WebSocket closed:", event);
      // 如果不是主动关闭，则重连
      if (!this.isManualClose) {
        setTimeout(() => this.reconnect(), this.reconnectDelay);
      }
    };
  }

  reconnect() {
    console.log("Reconnecting WebSocket...");
    this.connect();
  }

  // 定时检查连接状态
  startHeartbeat() {
    this.heartbeatTimer = setInterval(() => {
      if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
        console.warn("WebSocket not open. Attempting to reconnect...");
        this.reconnect();
      } else {
        // 发送信息
        this.ws.send(JSON.stringify({'cmd':'heartbeat','msg':'ping', 'liveId': this.liveId, 'userId': this.userId}));
        console.log("WebSocket is healthy.");
      }
    }, this.checkInterval);
  }

  // 主动关闭 WebSocket 连接，并清除定时任务
  close() {
    this.isManualClose = true;
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer);
    }
    if (this.ws) {
      this.ws.close();
    }
  }

  // 发送消息方法
  send(message) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(message);
    } else {
      console.error("WebSocket is not open. Message not sent.");
    }
  }
}
