'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 utils = require('./utils.js');

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

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

function testPut(factory, options) {
  const describe = mocha.getDescribe(options);
  const it = mocha.getIt(options);
  describe('.dht.put', 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 put a value to the DHT', async function () {
      const {cid} = await nodeA.add('should put a value to the DHT');
      const publish = await nodeA.name.publish(cid);
      let record;
      for await (const event of nodeA.dht.get(`/ipns/${ publish.name }`)) {
        if (event.name === 'VALUE') {
          record = event.value;
          break;
        }
      }
      if (!record) {
        throw new Error('Could not find value');
      }
      const events = await all__default["default"](nodeA.dht.put(`/ipns/${ publish.name }`, record, { verbose: true }));
      const peerResponse = events.filter(event => event.name === 'PEER_RESPONSE').pop();
      if (!peerResponse || peerResponse.name !== 'PEER_RESPONSE') {
        throw new Error('Did not get peer response');
      }
      const nodeBId = await nodeB.id();
      chai_js.expect(peerResponse.from).to.be.equal(nodeBId.id);
    });
  });
}

exports.testPut = testPut;
