"use strict";

import { xml } from '@xmpp/client';
import { createTimeoutPromise } from './createTimeoutPromise.xmpp';
let presenceIdCounter = 0;
const nextPresenceId = () => `presenceInRoom-${Date.now().toString(36)}-${(++presenceIdCounter).toString(36)}`;
export const presenceInRoom = async (client, roomJID, delay = 2000) => {
  let stanzaHandler;
  const unsubscribe = () => client.off('stanza', stanzaHandler);
  const stanzaId = nextPresenceId();
  return new Promise(async (resolve, reject) => {
    let settled = false;
    const finish = (cb, value) => {
      if (settled) {
        return;
      }
      settled = true;
      setTimeout(() => {
        unsubscribe();
        cb(value);
      }, delay);
    };
    stanzaHandler = stanza => {
      if (stanza.is('presence') && stanza.attrs.id === stanzaId && stanza.attrs.from?.startsWith(roomJID)) {
        finish(resolve, stanza);
      }
    };
    client.on('stanza', stanzaHandler);
    const presence = xml('presence', {
      from: client.jid?.toString(),
      to: `${roomJID}/${client.jid?.getLocal()}`,
      id: stanzaId
    }, xml('x', {
      xmlns: 'http://jabber.org/protocol/muc'
    }));
    try {
      await client.send(presence);
    } catch (err) {
      unsubscribe();
      return [];
    }
    await createTimeoutPromise(2000, unsubscribe).catch(reject);
  });
};
//# sourceMappingURL=presenceInRoom.xmpp.js.map