/*
 * 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
 */
cryptolib.modules.primitives = cryptolib.modules.primitives || {};

/**
 * Defines primitives services.
 * @namespace primitives/service
 */
cryptolib.modules.primitives.service = function(box) {
  'use strict';

  box.primitives = box.primitives || {};
  /**
   * A module that holds primitives API.
   * @exports primitives/service
   */
  box.primitives.service = {};

  var securerandomFactory, messageDigestFactory, secretKeyGeneratorFactory;

  cryptolib(
      'primitives.securerandom', 'commons.exceptions',
      'primitives.messagedigest', 'primitives.derivation', function(box) {
        securerandomFactory =
            new box.primitives.securerandom.factory.SecureRandomFactory();
        messageDigestFactory =
            new box.primitives.messagedigest.factory.MessageDigestFactory();
        secretKeyGeneratorFactory =
            new box.primitives.derivation.factory.SecretKeyGeneratorFactory();
      });

  /**
   * Provides a random bytes generator.
   * @function
   * @returns {primitives/securerandom.CryptoScytlRandomBytes} a CryptoRandomBytes object.
   */
  box.primitives.service.getCryptoRandomBytes = function() {
    return securerandomFactory.getCryptoRandomBytes();
  };

  /**
   * Provides a random integer generator.
   * @function
   * @returns {primitives/securerandom.CryptoScytlRandomInteger} a CryptoRandomInteger object.
   */
  box.primitives.service.getCryptoRandomInteger = function() {
    return securerandomFactory.getCryptoRandomInteger();
  };

  /**
   * Generates a hash for the given data.
   * @function
   * @parameter {array} ArrayDataBase64 the input data for the hash.
   * @returns {string} the hash, as a string in Base64 encoded format.
   */
  box.primitives.service.getHash = function(ArrayDataBase64) {
    var hashFunction = messageDigestFactory.getCryptoMessageDigest();
    hashFunction.start();
    hashFunction.update(ArrayDataBase64);
    return hashFunction.digest();
  };

  /**
   * Provides a derived secret key generator.
   * @function
   * @returns {primitives/derivation.CryptoForgePBKDFSecretKeyGenerator} a the pbkdf Generator.
   */
  box.primitives.service.getPbkdfSecretKeyGenerator = function() {
    return secretKeyGeneratorFactory.createPBKDF();
  };
};
