/*
 * 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 KeyStoreService = require('./service');
var validator = require('./input-validator');

module.exports = {
  /**
   * Creates a new KeyStoreService object, which encapsulates a key store
   * service.
   *
   * @function newService
   * @global
   * @param {Object}
   *            [options] An object containing optional arguments.
   * @param {Policy}
   *            [options.policy=Default policy] The cryptographic policy to
   *            use.
   * @param {PbkdfRandomService}
   *            [options.pbkdfRandomService=Created internally] The PBKDF
   *            service to use.
   * @param {SymmetricCryptographyService}
   *            [options.symmetricCryptographyService=Created internally] The
   *            symmetric cryptography service to use.
   * @param {ElGamalCryptographyService}
   *            [options.elGamalCryptographyService=Created internally] The
   *            ElGamal cryptography service to use.
   * @returns {KeyStoreService} The new KeyStoreService object.
   * @throws {Error}
   *             If the input data validation fails.
   * @example <caption> How to use a cryptographic policy that sets the PBKDF
   *          derivation key length to 16 bytes</caption>
   *
   * var cryptoPolicy = require('scytl-cryptopolicy');
   * var keyStore = require('scytl-keystore');
   *
   * var myPolicy = cryptoPolicy.newInstance();
   *
   * myPolicy.primitives.keyDerivation.pbkdf.keyLengthBytes =
   * cryptoPolicy.options.primitives.keyDerivation.pbkdf.keyLengthBytes.KL_16;
   *
   * var keyStoreService = keyStore.newService({policy: myPolicy});
   */
  newService: function(options) {
    checkData(options);

    return new KeyStoreService(options);
  }
};

function checkData(options) {
  options = options || {};

  if (typeof options.policy !== 'undefined') {
    validator.checkIsObjectWithProperties(
        options.policy, 'Cryptographic policy provided to key store service');
  }

  if (typeof options.pbkdfService !== 'undefined') {
    validator.checkIsObjectWithProperties(
        options.pbkdfService,
        'PBKDF service object provided to key store service');
  }

  if (typeof options.symmetricCryptographyService !== 'undefined') {
    validator.checkIsObjectWithProperties(
        options.symmetricCryptographyService,
        'Symmetric cryptography service object provided to key store service');
  }

  if (typeof options.elGamalCryptographyService !== 'undefined') {
    validator.checkIsObjectWithProperties(
        options.elGamalCryptographyService,
        'ElGamal cryptography service object provided to key store service');
  }
}
