/**
 * WebSocket 通用工具类
 * @author Lexcubia
 * @date 2024-04-25
 */

class WebSocketClient {
  constructor(config) {
    this.socket = null;
    this.msgHandle = config.msgHandle;
    this.stateHandle = config.stateHandle;
    this.config = config;
  }

  /**
   * 建立 WebSocket 连接
   * @param {string} url - WebSocket 服务器地址
   * @returns {boolean} - 连接是否成功
   */
  connect(url) {
    if (!url) {
      console.error('WebSocket URL 不能为空');
      return false;
    }

    if (!url.match(/wss?:\S*/)) {
      console.error('WebSocket URL 格式不正确');
      return false;
    }

    if (!('WebSocket' in window)) {
      console.error('当前浏览器不支持 WebSocket');
      return false;
    }

    try {
      this.socket = new WebSocket(url);
      this.socket.onopen = this._onOpen.bind(this);
      this.socket.onclose = this._onClose.bind(this);
      this.socket.onmessage = this._onMessage.bind(this);
      this.socket.onerror = this._onError.bind(this);
      return true;
    } catch (error) {
      console.error('WebSocket 连接失败:', error);
      return false;
    }
  }

  /**
   * 关闭 WebSocket 连接
   */
  disconnect() {
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  }

  /**
   * 发送数据
   * @param {any} data - 要发送的数据
   */
  send(data) {
    if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
      console.error('WebSocket 未连接');
      return;
    }

    try {
      // 如果是ArrayBuffer或TypedArray，直接发送二进制
      if (data instanceof ArrayBuffer) {
        this.socket.send(data);
      } else if (
        data instanceof Int8Array ||
        data instanceof Uint8Array ||
        data instanceof Int16Array ||
        data instanceof Uint16Array ||
        data instanceof Int32Array ||
        data instanceof Uint32Array ||
        data instanceof Float32Array ||
        data instanceof Float64Array
      ) {
        this.socket.send(data.buffer);
      } else if (typeof data === 'object') {
        // 仅普通对象才转JSON
        data = JSON.stringify(data);
        this.socket.send(data);
      } else {
        this.socket.send(data);
      }
    } catch (error) {
      console.error('发送数据失败:', error);
    }
  }

  /**
   * 连接建立时的回调
   * @private
   */
  _onOpen() {
    console.log('WebSocket 连接成功');
    this.stateHandle(0);
    
    // 发送初始化配置
    const initConfig = {
      chunk_size: [5, 10, 5],
      wav_name: 'h5',
      is_speaking: true,
      chunk_interval: 10,
      itn: this.config.itn || false,
      mode: this.config.mode || '2pass',
      ...this.config.initConfig
    };

    this.send(initConfig);
  }

  /**
   * 连接关闭时的回调
   * @private
   */
  _onClose() {
    console.log('WebSocket 连接关闭');
    this.stateHandle(1);
  }

  /**
   * 收到消息时的回调
   * @private
   */
  _onMessage(event) {
    this.msgHandle(event);
  }

  /**
   * 发生错误时的回调
   * @private
   */
  _onError(error) {
    console.error('WebSocket 错误:', error);
    this.stateHandle(2);
  }
}

export default WebSocketClient; 