'use strict';

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

var fromString = require('uint8arrays/from-string');
var dagPB = require('@ipld/dag-pb');
var cid = require('multiformats/cid');
var sha2 = require('multiformats/hashes/sha2');
var chai_js = require('aegir/utils/chai.js');
var mocha = require('../../utils/mocha.js');

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n["default"] = e;
  return Object.freeze(n);
}

var dagPB__namespace = /*#__PURE__*/_interopNamespace(dagPB);

function testRmLink(factory, options) {
  const describe = mocha.getDescribe(options);
  const it = mocha.getIt(options);
  describe('.object.patch.rmLink', function () {
    this.timeout(80 * 1000);
    let ipfs;
    before(async () => {
      ipfs = (await factory.spawn()).api;
    });
    after(() => factory.clean());
    it('should remove a link from an existing node', async () => {
      const obj1 = {
        Data: fromString.fromString('patch test object 1'),
        Links: []
      };
      const obj2 = {
        Data: fromString.fromString('patch test object 2'),
        Links: []
      };
      const nodeCid = await ipfs.object.put(obj1);
      const childCid = await ipfs.object.put(obj2);
      const child = await ipfs.object.get(childCid);
      const childBuf = dagPB__namespace.encode(child);
      const childAsDAGLink = {
        Name: 'my-link',
        Tsize: childBuf.length,
        Hash: cid.CID.createV0(await sha2.sha256.digest(childBuf))
      };
      const parentCid = await ipfs.object.patch.addLink(nodeCid, childAsDAGLink);
      const withoutChildCid = await ipfs.object.patch.rmLink(parentCid, childAsDAGLink);
      chai_js.expect(withoutChildCid).to.not.deep.equal(parentCid);
      chai_js.expect(withoutChildCid).to.deep.equal(nodeCid);
    });
    it('returns error for request without arguments', () => {
      return chai_js.expect(ipfs.object.patch.rmLink(null, null)).to.eventually.be.rejected.and.be.an.instanceOf(Error);
    });
    it('returns error for request only one invalid argument', () => {
      return chai_js.expect(ipfs.object.patch.rmLink('invalid', null)).to.eventually.be.rejected.and.be.an.instanceOf(Error);
    });
    it('returns error for request with invalid first argument', () => {
      const root = '';
      const link = 'foo';
      return chai_js.expect(ipfs.object.patch.rmLink(root, link)).to.eventually.be.rejected.and.be.an.instanceOf(Error);
    });
  });
}

exports.testRmLink = testRmLink;
