'use strict';

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

var nanoid = require('nanoid');
var chai_js = require('aegir/utils/chai.js');
var mocha = require('../utils/mocha.js');
var libp2pCrypto = require('libp2p-crypto');

const {
  supportedKeys,
  import: importKey
} = libp2pCrypto.keys;
function testGen(factory, options) {
  const describe = mocha.getDescribe(options);
  const it = mocha.getIt(options);
  describe('.key.gen', () => {
    const keyTypes = [
      {
        opts: {
          type: 'rsa',
          size: 2048
        },
        expectedType: supportedKeys.rsa.RsaPrivateKey
      },
      {
        opts: { type: 'ed25519' },
        expectedType: supportedKeys.ed25519.Ed25519PrivateKey
      },
      {
        opts: {},
        expectedType: supportedKeys.ed25519.Ed25519PrivateKey
      }
    ];
    let ipfs;
    before(async () => {
      ipfs = (await factory.spawn()).api;
    });
    after(() => factory.clean());
    keyTypes.forEach(kt => {
      it(`should generate a new ${ kt.opts.type || 'default' } key`, async function () {
        this.timeout(20 * 1000);
        const name = nanoid.nanoid();
        const key = await ipfs.key.gen(name, kt.opts);
        chai_js.expect(key).to.exist();
        chai_js.expect(key).to.have.property('name', name);
        chai_js.expect(key).to.have.property('id');
        try {
          const password = nanoid.nanoid() + '-' + nanoid.nanoid();
          const exported = await ipfs.key.export(name, password);
          const imported = await importKey(exported, password);
          chai_js.expect(imported).to.be.an.instanceOf(kt.expectedType);
        } catch (err) {
          if (err.code === 'ERR_NOT_IMPLEMENTED') {
            this.skip('Cannot verify key type');
          }
          throw err;
        }
      });
    });
  });
}

exports.testGen = testGen;
