'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 toString = require('uint8arrays/to-string');
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 testGet(factory, options) {
  const describe = mocha.getDescribe(options);
  const it = mocha.getIt(options);
  describe('.dht.get', 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 getting a value from the DHT', async () => {
      const data = await nodeA.add('should put a value to the DHT');
      const publish = await nodeA.name.publish(data.cid);
      await testTimeout(() => drain__default["default"](nodeB.dht.get(`/ipns/${ publish.name }`, { timeout: 1 })));
    });
    it('should error when getting a non-existent key from the DHT', async () => {
      const key = '/ipns/k51qzi5uqu5dl0dbfddy2wb42nvbc6anyxnkrguy5l0h0bv9kaih6j6vqdskqk';
      const events = await all__default["default"](nodeA.dht.get(key));
      chai_js.expect(events.filter(event => event.name === 'VALUE')).to.be.empty();
      chai_js.expect(events.filter(event => event.name === 'QUERY_ERROR')).to.not.be.empty();
    });
    it('should get a value after it was put on another node', async () => {
      const data = await nodeA.add('should put a value to the DHT');
      const publish = await nodeA.name.publish(data.cid);
      const events = await all__default["default"](nodeA.dht.get(`/ipns/${ publish.name }`));
      const valueEvent = events.filter(event => event.name === 'VALUE').pop();
      if (!valueEvent || valueEvent.name !== 'VALUE') {
        throw new Error('Value event not found');
      }
      chai_js.expect(toString.toString(valueEvent.value)).to.contain(data.cid.toString());
    });
  });
}

exports.testGet = testGet;
