"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.buildXmppClientKey = buildXmppClientKey;
exports.default = void 0;
exports.getGlobalXmppClient = getGlobalXmppClient;
exports.getGlobalXmppClientKey = getGlobalXmppClientKey;
exports.getReusableXmppClientByKey = getReusableXmppClientByKey;
exports.isXmppClientReusable = isXmppClientReusable;
exports.requireXmppClient = requireXmppClient;
exports.setGlobalXmppClient = setGlobalXmppClient;
exports.withXmppClientInitLock = withXmppClientInitLock;
let currentClient = null;
let currentClientKey = '';
const initLocks = new Map();
const DEFAULT_DEV_SERVER = 'xmpp.chat.ethora.com';
function buildXmppClientKey(username, xmppSettings) {
  const devServer = xmppSettings?.devServer || DEFAULT_DEV_SERVER;
  const host = xmppSettings?.host || '';
  const conference = xmppSettings?.conference || '';
  return `${username}|${devServer}|${host}|${conference}`;
}
function isXmppClientReusable(client) {
  if (!client) {
    return false;
  }
  return client.status === 'online' || client.status === 'connecting';
}
function setGlobalXmppClient(client, key) {
  currentClient = client;
  currentClientKey = client ? key || currentClientKey || '' : '';
}
function getGlobalXmppClient() {
  return currentClient;
}
function getGlobalXmppClientKey() {
  return currentClientKey;
}
function getReusableXmppClientByKey(key) {
  if (!key || key !== currentClientKey) {
    return null;
  }
  if (!isXmppClientReusable(currentClient)) {
    return null;
  }
  return currentClient;
}
async function withXmppClientInitLock(key, init) {
  const existing = initLocks.get(key);
  if (existing) {
    return existing;
  }
  const createdPromise = init().finally(() => {
    if (initLocks.get(key) === createdPromise) {
      initLocks.delete(key);
    }
  });
  initLocks.set(key, createdPromise);
  return createdPromise;
}
function requireXmppClient() {
  if (!currentClient) {
    throw new Error('XMPP client is not initialized');
  }
  return currentClient;
}
var _default = exports.default = {
  buildXmppClientKey,
  isXmppClientReusable,
  setGlobalXmppClient,
  getGlobalXmppClient,
  getGlobalXmppClientKey,
  getReusableXmppClientByKey,
  withXmppClientInitLock,
  requireXmppClient
};
//# sourceMappingURL=clientRegistry.js.map