/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
/* jshint node:true */
'use strict';

var forge = require('node-forge');

module.exports = PrivateKeyCollector;

var collectEntropy_, privateKey_, pinEntropy_;

/**
 * Add an entropy collector based on a private key. The amount of randomness
 * (entropy) depends on the pin that is used for Private Key generating.
 *
 * @function
 * @param pem
 *            {string} private key, as string in PEM format.
 * @param entropy
 *            the amount of randomness that can be extracted from the
 *            Private Key.
 */
function PrivateKeyCollector(
    collectEntropyCallback, privateKeyPem, pinEntropy) {
  if (!privateKeyPem) {
    throw new Error('A private key is required');
  }

  if (isNaN(pinEntropy) || (pinEntropy < 1)) {
    throw new Error('A positive PIN entropy is required');
  }

  collectEntropy_ = collectEntropyCallback;
  privateKey_ = forge.pki.privateKeyFromPem(privateKeyPem);
  pinEntropy_ = pinEntropy;
}

PrivateKeyCollector.prototype = {
  pkCollector: true,
  startCollector: function() {
    collectEntropy_(privateKey_.d, pinEntropy_);
  },

  stopCollector: function() {
    // just executed once, so no need to execute anything else
    return true;
  },

  getPrivateKey: function() {
    return privateKey_;
  }
};