"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.presenceInRoom = void 0;
var _client = require("@xmpp/client");
var _createTimeoutPromise = require("./createTimeoutPromise.xmpp");
let presenceIdCounter = 0;
const nextPresenceId = () => `presenceInRoom-${Date.now().toString(36)}-${(++presenceIdCounter).toString(36)}`;
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 = (0, _client.xml)('presence', {
      from: client.jid?.toString(),
      to: `${roomJID}/${client.jid?.getLocal()}`,
      id: stanzaId
    }, (0, _client.xml)('x', {
      xmlns: 'http://jabber.org/protocol/muc'
    }));
    try {
      await client.send(presence);
    } catch (err) {
      unsubscribe();
      return [];
    }
    await (0, _createTimeoutPromise.createTimeoutPromise)(2000, unsubscribe).catch(reject);
  });
};
exports.presenceInRoom = presenceInRoom;
//# sourceMappingURL=presenceInRoom.xmpp.js.map