'use strict';

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

var chai_js = require('aegir/utils/chai.js');
var mocha = require('../utils/mocha.js');
var all = require('it-all');
var drain = require('it-drain');
var testTimeout = require('../utils/test-timeout.js');
var utils = require('./utils.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var all__default = /*#__PURE__*/_interopDefaultLegacy(all);
var drain__default = /*#__PURE__*/_interopDefaultLegacy(drain);

function testFindProvs(factory, options) {
  const describe = mocha.getDescribe(options);
  const it = mocha.getIt(options);
  describe('.dht.findProvs', function () {
    this.timeout(80 * 1000);
    let nodeA;
    let nodeB;
    let nodeC;
    before(async () => {
      nodeA = (await factory.spawn()).api;
      nodeB = (await factory.spawn()).api;
      nodeC = (await factory.spawn()).api;
      await utils.ensureReachable(nodeB, nodeA);
      await utils.ensureReachable(nodeC, nodeB);
    });
    after(() => factory.clean());
    let providedCid;
    before('add providers for the same cid', async function () {
      const cids = await Promise.all([
        nodeB.object.new('unixfs-dir'),
        nodeC.object.new('unixfs-dir')
      ]);
      providedCid = cids[0];
      await Promise.all([
        all__default["default"](nodeB.dht.provide(providedCid)),
        all__default["default"](nodeC.dht.provide(providedCid))
      ]);
    });
    it('should respect timeout option when finding providers on the DHT', () => {
      return testTimeout(() => drain__default["default"](nodeA.dht.findProvs(providedCid, { timeout: 1 })));
    });
    it('should be able to find providers', async function () {
      const providerIds = [];
      for await (const event of nodeA.dht.findProvs(providedCid)) {
        if (event.name === 'PROVIDER') {
          providerIds.push(...event.providers.map(prov => prov.id));
        }
      }
      const nodeBId = await nodeB.id();
      const nodeCId = await nodeC.id();
      chai_js.expect(providerIds).to.include(nodeBId.id);
      chai_js.expect(providerIds).to.include(nodeCId.id);
    });
  });
}

exports.testFindProvs = testFindProvs;
