"use strict";

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