'use strict';

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

var fromString = require('uint8arrays/from-string');
var identity = require('multiformats/hashes/identity');
var cid = require('multiformats/cid');
var chai_js = require('aegir/utils/chai.js');
var mocha = require('../utils/mocha.js');
var testTimeout = require('../utils/test-timeout.js');

function testGet(factory, options) {
  const describe = mocha.getDescribe(options);
  const it = mocha.getIt(options);
  describe('.block.get', () => {
    const data = fromString.fromString('blorb');
    let ipfs;
    let cid$1;
    before(async () => {
      ipfs = (await factory.spawn()).api;
      cid$1 = await ipfs.block.put(data);
    });
    after(() => factory.clean());
    it('should respect timeout option when getting a block', () => {
      return testTimeout(() => ipfs.block.get(cid.CID.parse('QmPv52ekjS75L4JmHpXVeuJ5uX2ecSfSZo88NSyxwA3rA3'), { timeout: 1 }));
    });
    it('should get by CID', async () => {
      const block = await ipfs.block.get(cid$1);
      chai_js.expect(block).to.equalBytes(fromString.fromString('blorb'));
    });
    it('should get an empty block', async () => {
      const cid = await ipfs.block.put(new Uint8Array(0), {
        format: 'dag-pb',
        mhtype: 'sha2-256',
        version: 0
      });
      const block = await ipfs.block.get(cid);
      chai_js.expect(block).to.equalBytes(new Uint8Array(0));
    });
    it('should get a block added as CIDv0 with a CIDv1', async () => {
      const input = fromString.fromString(`TEST${ Math.random() }`);
      const cidv0 = await ipfs.block.put(input);
      chai_js.expect(cidv0.version).to.equal(0);
      const cidv1 = cidv0.toV1();
      const block = await ipfs.block.get(cidv1);
      chai_js.expect(block).to.equalBytes(input);
    });
    it('should get a block added as CIDv1 with a CIDv0', async () => {
      const input = fromString.fromString(`TEST${ Math.random() }`);
      const cidv1 = await ipfs.block.put(input, {
        version: 1,
        format: 'dag-pb'
      });
      chai_js.expect(cidv1.version).to.equal(1);
      const cidv0 = cidv1.toV0();
      const block = await ipfs.block.get(cidv0);
      chai_js.expect(block).to.equalBytes(input);
    });
    it('should get a block with an identity CID, without putting first', async () => {
      const identityData = fromString.fromString('A16461736466190144', 'base16upper');
      const identityHash = await identity.identity.digest(identityData);
      const identityCID = cid.CID.createV1(identity.identity.code, identityHash);
      const block = await ipfs.block.get(identityCID);
      chai_js.expect(block).to.equalBytes(identityData);
    });
    it('should return an error for an invalid CID', () => {
      return chai_js.expect(ipfs.block.get('Non-base58 character')).to.eventually.be.rejected.and.be.an.instanceOf(Error);
    });
  });
}

exports.testGet = testGet;
