'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var env_js = require('ipfs-utils/src/env.js');
var utils = require('./utils.js');
var mocha = require('../utils/mocha.js');
var waitFor = require('../utils/wait-for.js');

function testUnsubscribe(factory, options) {
  const describe = mocha.getDescribe(options);
  const it = mocha.getIt(options);
  describe('.pubsub.unsubscribe', function () {
    this.timeout(80 * 1000);
    let ipfs;
    before(async () => {
      ipfs = (await factory.spawn()).api;
    });
    after(() => factory.clean());
    const count = env_js.isBrowser || env_js.isWebWorker || env_js.isElectronRenderer ? 5 : 10;
    it(`should subscribe and unsubscribe ${ count } times`, async () => {
      const someTopic = utils.getTopic();
      const handlers = Array.from(Array(count), () => msg => {
      });
      for (let i = 0; i < count; i++) {
        await ipfs.pubsub.subscribe(someTopic, handlers[i]);
      }
      for (let i = 0; i < count; i++) {
        await ipfs.pubsub.unsubscribe(someTopic, handlers[i]);
      }
      await waitFor(async () => {
        const subs = await ipfs.pubsub.ls();
        return subs.length === 0;
      }, {
        interval: 1000,
        timeout: 30000,
        name: 'subscriptions to be empty'
      });
    });
    it(`should subscribe ${ count } handlers and unsubscribe once with no reference to the handlers`, async () => {
      const someTopic = utils.getTopic();
      for (let i = 0; i < count; i++) {
        await ipfs.pubsub.subscribe(someTopic, msg => {
        });
      }
      await ipfs.pubsub.unsubscribe(someTopic);
      await waitFor(async () => {
        const subs = await ipfs.pubsub.ls();
        return subs.length === 0;
      }, {
        interval: 1000,
        timeout: 30000,
        name: 'subscriptions to be empty'
      });
    });
  });
}

exports.testUnsubscribe = testUnsubscribe;
