const helpers = require('./helpers');
const path = require('path');
const fs = require('fs');
const Constants = require('./constants');

test('verify signature success', () => {
  return helpers
    .verifySignature(
      path.resolve('test/test_verify_signature.dat'),
      path.resolve('test/test_verify_signature.dat.sig'),
      path.resolve('blockstorage_dev_public.pem'))
    .then(stdout => {
      expect(stdout).toBeDefined();
    });
});

test('verify signature fail', () => {
  return expect(helpers
    .verifySignature(
      path.resolve('test/test_verify_signature_fail.dat'),
      path.resolve('test/test_verify_signature.dat.sig'),
      path.resolve('blockstorage_dev_public.pem')))
  .rejects
  .toThrow()
});

test('create temp signature files', () => {
  const b64signature = fs.readFileSync(path.resolve('test/test_create_signature.sig.b64'), {encoding: 'utf8'}).replace(/(\r\n|\n|\r)/gm,"");
  const data = helpers
    .createSignatureFiles(
      b64signature,
      Constants.DEV_PUBLIC_KEY);
  expect(data).toBeDefined();
  expect(data.PublicKeyFile).toBeDefined();
  expect(data.SignatureFile).toBeDefined();

  expect(fs.statSync(data.SignatureFile).isFile()).toBe(true);
  expect(fs.statSync(data.PublicKeyFile).isFile()).toBe(true);

  const b64signature2 = fs.readFileSync(data.SignatureFile).toString('base64').replace(/(\r\n|\n|\r)/gm,"");
  expect(b64signature2).toEqual(b64signature);

  expect(fs.readFileSync(data.PublicKeyFile, {encoding: 'utf8'})).toEqual(Constants.DEV_PUBLIC_KEY);
  fs.unlinkSync(data.PublicKeyFile);
  fs.unlinkSync(data.SignatureFile);
});

test('verify sha56 success', ()=> {
  const hash = fs.readFileSync('test/test_verify_sha256.dat.sha256', {encoding: 'utf8'});
  return expect(helpers.verifyHash(path.resolve('test/test_verify_sha256.dat'), hash))
    .resolves.toBe(hash)
});

test('verify sha56 fail', ()=> {
  const hash = fs.readFileSync('test/test_verify_sha256.dat.sha256', {encoding: 'utf8'});
  return expect(helpers.verifyHash(path.resolve('test/test_verify_sha256_fail.dat'), hash))
    .rejects.toThrow();
});