var h = Object.defineProperty;
var g = (t, n, e) => n in t ? h(t, n, { enumerable: !0, configurable: !0, writable: !0, value: e }) : t[n] = e;
var r = (t, n, e) => g(t, typeof n != "symbol" ? n + "" : n, e);
import { MqttClient as u } from "./mqtt.mjs";
const s = class s {
  constructor() {
    r(this, "connections", /* @__PURE__ */ new Map());
    r(this, "connectionConfigs", /* @__PURE__ */ new Map());
  }
  static getInstance() {
    return s.instance || (s.instance = new s()), s.instance;
  }
  /**
   * 生成连接的唯一标识
   */
  generateConnectionKey(n) {
    return JSON.stringify(n);
  }
  /**
   * 获取或创建连接
   */
  async getOrCreateConnection(n, e) {
    const o = this.generateConnectionKey(n), i = this.connections.get(o);
    if (i && i.isConnected())
      return i;
    this.connections.entries().forEach(([C]) => {
      const l = JSON.parse(C);
      l.uuid === n.uuid && this.closeConnection(l);
    });
    const a = new u(n, e);
    this.connections.set(o, a), this.connectionConfigs.set(o, n);
    try {
      await a.connect();
    } catch {
    }
    return a;
  }
  /**
   * 检查连接是否存在
   */
  hasConnection(n) {
    const e = this.generateConnectionKey(n), o = this.connections.get(e);
    return o !== void 0 && o.isConnected();
  }
  /**
   * 获取所有连接
   */
  getAllConnections() {
    return new Map(this.connections);
  }
  /**
   * 关闭指定连接
   */
  closeConnection(n) {
    const e = this.generateConnectionKey(n), o = this.connections.get(e);
    return o ? (o.disconnect(), this.connections.delete(e), this.connectionConfigs.delete(e), !0) : !1;
  }
  /**
   * 关闭所有连接
   */
  closeAllConnections() {
    for (const [n, e] of this.connections)
      e.disconnect(), this.connections.delete(n), this.connectionConfigs.delete(n);
    return this.connections.clear(), this.connectionConfigs.clear(), !0;
  }
};
r(s, "instance");
let c = s;
const y = {
  /**
   * 获取连接池实例
   */
  getInstance: () => c.getInstance(),
  /**
   * 检查是否存在指定配置的连接
   */
  hasConnection: (t) => c.getInstance().hasConnection(t),
  /**
   * 关闭指定配置的连接
   */
  closeConnection: (t) => c.getInstance().closeConnection(t),
  /**
   * 关闭所有连接
   */
  closeAllConnections: () => {
    c.getInstance().closeAllConnections();
  },
  /**
   * 关闭并移除key中uuid为uuid的连接
   * @param uuid 连接的唯一标识
   */
  removeConnectionByUUID: (t) => {
    const n = c.getInstance();
    n.getAllConnections().entries().forEach(([o]) => {
      const i = JSON.parse(o);
      i.uuid.includes(t) && n.closeConnection(i);
    });
  }
};
export {
  c as MqttConnectionPool,
  y as MqttConnectionPoolManager
};
