var o = Object.defineProperty;
var r = (c, t, e) => t in c ? o(c, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : c[t] = e;
var i = (c, t, e) => r(c, typeof t != "symbol" ? t + "" : t, e);
import { WebSocketConnectionPool as l } from "./websocketConnectionPool.mjs";
class f {
  // 标记是否为主动断开
  constructor(t, e = {}) {
    i(this, "client", null);
    i(this, "config");
    i(this, "callbacks");
    i(this, "connectionState", "disconnected");
    i(this, "reconnectAttempts", 0);
    i(this, "reconnectTimer", null);
    i(this, "connectTimer", null);
    i(this, "isManualDisconnect", !1);
    this.config = t, this.callbacks = e;
  }
  /**
   * 连接到WebSocket服务器
   */
  async connect() {
    return new Promise((t, e) => {
      if (this.client && this.client.readyState === WebSocket.OPEN) {
        t();
        return;
      }
      this.connectionState = "connecting";
      try {
        this.config.protocols ? this.client = new WebSocket(this.config.url, this.config.protocols) : this.client = new WebSocket(this.config.url), this.config.binaryType && (this.client.binaryType = this.config.binaryType), this.config.timeout && (this.connectTimer = setTimeout(() => {
          this.client && this.client.readyState === WebSocket.CONNECTING && (this.client.close(), e(new Error("WebSocket连接超时")));
        }, this.config.timeout)), this.client.onopen = () => {
          if (this.connectTimer && (clearTimeout(this.connectTimer), this.connectTimer = null), this.connectionState = "connected", this.reconnectAttempts = 0, this.isManualDisconnect = !1, this.config.isMessage && this.config.message && this.client && this.client.readyState === WebSocket.OPEN)
            try {
              const n = typeof this.config.message == "string" ? this.config.message : JSON.stringify(this.config.message);
              this.client.send(n);
            } catch {
            }
          this.callbacks.onOpen && this.callbacks.onOpen(), t();
        }, this.client.onclose = () => {
          this.connectTimer && (clearTimeout(this.connectTimer), this.connectTimer = null), this.connectionState = "disconnected", !this.isManualDisconnect && (this.callbacks.onClose && this.callbacks.onClose(), this.config.reconnect && this.reconnectAttempts < (this.config.maxReconnectAttempts || 1 / 0) && this.handleReconnect());
        }, this.client.onmessage = (n) => {
          if (this.callbacks.onMessage) {
            let s = n.data;
            if (typeof s == "string")
              try {
                s = JSON.parse(s);
              } catch {
              }
            this.callbacks.onMessage(s);
          }
        }, this.client.onerror = (n) => {
          this.connectTimer && (clearTimeout(this.connectTimer), this.connectTimer = null), this.connectionState = "error", this.callbacks.onError && this.callbacks.onError(n), e(n);
        };
      } catch (n) {
        this.connectionState = "error", e(n);
      }
    });
  }
  /**
   * 断开WebSocket连接
   */
  disconnect() {
    this.isManualDisconnect = !0, this.reconnectTimer && (clearTimeout(this.reconnectTimer), this.reconnectTimer = null), this.connectTimer && (clearTimeout(this.connectTimer), this.connectTimer = null), this.client && (this.client.close(), this.client = null, this.connectionState = "disconnected");
  }
  /**
   * 发送消息
   */
  send(t) {
    if (this.client && this.client.readyState === WebSocket.OPEN) {
      const e = typeof t == "string" ? t : JSON.stringify(t);
      this.client.send(e);
    }
  }
  /**
   * 检查是否已连接
   */
  isConnected() {
    return this.client !== null && this.client.readyState === WebSocket.OPEN;
  }
  /**
   * 获取连接状态
   */
  getConnectionState() {
    return this.connectionState;
  }
  /**
   * 处理重连
   */
  handleReconnect() {
    this.reconnectAttempts >= (this.config.maxReconnectAttempts || 1 / 0) || (this.connectionState = "reconnecting", this.reconnectAttempts++, this.callbacks.onReconnect && this.callbacks.onReconnect(), this.reconnectTimer = setTimeout(() => {
      this.connect().catch((t) => {
      });
    }, this.config.reconnectInterval || 3e3));
  }
}
function m(c, t) {
  return l.getInstance().getOrCreateConnection(c, t);
}
export {
  f as WebSocketClient,
  m as createWebSocketClient
};
