'use strict';

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

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

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

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

function testFindPeer(factory, options) {
  const describe = mocha.getDescribe(options);
  const it = mocha.getIt(options);
  describe('.dht.findPeer', function () {
    this.timeout(80 * 1000);
    let nodeA;
    let nodeB;
    before(async () => {
      nodeA = (await factory.spawn()).api;
      nodeB = (await factory.spawn()).api;
      await utils.ensureReachable(nodeA, nodeB);
    });
    after(() => factory.clean());
    it('should respect timeout option when finding a peer on the DHT', async () => {
      const nodeBId = await nodeB.id();
      await testTimeout(() => drain__default["default"](nodeA.dht.findPeer(nodeBId.id, { timeout: 1 })));
    });
    it('should find other peers', async () => {
      const nodeBId = await nodeB.id();
      const results = await all__default["default"](nodeA.dht.findPeer(nodeBId.id));
      const finalPeer = results.filter(event => event.name === 'FINAL_PEER').pop();
      if (!finalPeer || finalPeer.name !== 'FINAL_PEER') {
        throw new Error('No finalPeer event received');
      }
      const id = finalPeer.peer.id;
      const nodeAddresses = nodeBId.addresses.map(addr => addr.nodeAddress());
      const peerAddresses = finalPeer.peer.multiaddrs.map(ma => ma.nodeAddress());
      chai_js.expect(id).to.equal(nodeBId.id);
      chai_js.expect(peerAddresses).to.deep.include(nodeAddresses[0]);
    });
    it('should fail to find other peer if peer does not exist', async () => {
      const events = await all__default["default"](nodeA.dht.findPeer('Qmd7qZS4T7xXtsNFdRoK1trfMs5zU94EpokQ9WFtxdPxsZ'));
      chai_js.expect(events.filter(event => event.name === 'FINAL_PEER')).to.be.empty();
      chai_js.expect(events.filter(event => event.name === 'QUERY_ERROR')).to.not.be.empty();
    });
  });
}

exports.testFindPeer = testFindPeer;
