var a = Object.defineProperty;
var h = (i, n, t) => n in i ? a(i, n, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[n] = t;
var e = (i, n, t) => h(i, typeof n != "symbol" ? n + "" : n, t);
import b from "mqtt";
import { nanoid as f } from "nanoid";
import { MqttConnectionPool as u } from "./mqttConnectionPool.mjs";
class m {
  constructor(n, t = {}) {
    e(this, "client", null);
    e(this, "config");
    e(this, "callbacks");
    e(this, "connectionState", "disconnected");
    e(this, "subscriptions", /* @__PURE__ */ new Map());
    this.config = n, this.callbacks = t;
  }
  /**
   * 连接到MQTT服务器
   */
  async connect() {
    return new Promise((n, t) => {
      if (this.client && this.client.connected) {
        n();
        return;
      }
      this.connectionState = "connecting";
      const o = {
        clientId: f(),
        username: this.config.username,
        password: this.config.password,
        keepalive: this.config.keepalive || 60,
        reconnectPeriod: this.config.reconnectPeriod || 0,
        // 禁用自动重连，使用自定义重连逻辑
        connectTimeout: this.config.connectTimeout || 3e4,
        clean: this.config.clean !== !1,
        rejectUnauthorized: this.config.rejectUnauthorized !== !1
      }, l = `${this.config.protocol}://${this.config.host}:${this.config.port}${this.config.endpoint}`;
      try {
        this.client = b.connect(l, o), this.client.on("connect", () => {
          this.connectionState = "connected", this.resubscribeTopics(), this.callbacks.onConnect && this.callbacks.onConnect(), n();
        }), this.client.on("disconnect", () => {
          this.connectionState = "disconnected", this.callbacks.onDisconnect && this.callbacks.onDisconnect();
        }), this.client.on("close", () => {
          this.connectionState = "disconnected", this.callbacks.onClose && this.callbacks.onClose(), t(new Error("MQTT连接关闭"));
        }), this.client.on("error", (c) => {
          this.connectionState = "error", this.callbacks.onError && this.callbacks.onError(c), t(c);
        }), this.client.on("message", (c, r) => {
          this.callbacks.onMessage && this.callbacks.onMessage(c, r);
          const s = this.subscriptions.get(c);
          s && s.callback(c, r);
        }), this.client.on("reconnect", () => {
          this.connectionState = "reconnecting", this.callbacks.onReconnect && this.callbacks.onReconnect();
        });
      } catch (c) {
        this.connectionState = "error", t(c);
      }
    });
  }
  /**
   * 断开MQTT连接
   */
  disconnect() {
    this.client && (this.client.end(!0), this.client = null, this.connectionState = "disconnected");
  }
  /**
   * 订阅主题
   */
  subscribe(n, t = 0, o) {
    return new Promise((l, c) => {
      if (!this.client || !this.client.connected) {
        c(new Error("MQTT客户端未连接"));
        return;
      }
      const r = { qos: t };
      this.client.subscribe(n, r, (s) => {
        s ? c(s) : (o && this.subscriptions.set(n, { qos: t, callback: o }), l());
      });
    });
  }
  /**
   * 检查是否已连接
   */
  isConnected() {
    return this.client !== null && this.client.connected;
  }
  /**
   * 获取连接状态
   */
  getConnectionState() {
    return this.connectionState;
  }
  /**
   * 重新订阅之前的主题
   */
  resubscribeTopics() {
    for (const [n, t] of this.subscriptions)
      this.subscribe(n, t.qos, t.callback).catch(
        (o) => {
        }
      );
  }
}
function C(i, n) {
  return u.getInstance().getOrCreateConnection(i, n);
}
export {
  m as MqttClient,
  C as createMqttClient
};
