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

module.exports = {
  /**
   * Creates a new DigitalEnvelopeService object, which encapsulates a digital
   * envelope service.
   *
   * @function newService
   * @global
   * @param {Object}
   *            [options] An object containing optional arguments.
   * @param {Policy}
   *            [options.policy=Default policy] The cryptographic policy to
   *            use.
   * @param {SymmetricCryptographyService}
   *            [options.symmetricCryptographyService=Created internally] The
   *            symmetric cryptography service to use.
   * @param {AsymmetricCryptographyService}
   *            [options.asymmetricCryptographyService=Created internally] The
   *            asymmetric cryptography service to use.
   * @returns {DigitalEnvelopeService} The new DigitalEnvelopeService object.
   * @throws {Error}
   *             If the input data validation fails.
   * @example <caption> How to use a cryptographic policy that sets the key
   *          length of the symmetric cipher used by the digital envelope to
   *          32 bytes</caption>
   *
   * var cryptoPolicy = require('scytl-cryptopolicy');
   * var digitalEnvelope = require('scytl-digitalenvelope');
   *
   * var myPolicy = cryptoPolicy.newInstance();
   *
   * myPolicy.digitalEnvelope.symmetric.cipher.algorithm.AES_GCM.keyLengthBytes=
   * cryptoPolicy.options.digitalEnvelope.symmetric.cipher.algorithm.AES_GCM.keyLengthBytes.KL_32;
   *
   * var digitalEnvelopeService = digitalEnvelope.newService({policy:
   * myPolicy});
   */
  newService: function(options) {
    checkData(options);

    return new DigitalEnvelopeService(options);
  }
};

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

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

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

  if (typeof options.asymmetricCryptographyService !== 'undefined') {
    validator.checkIsObjectWithProperties(
        options.asymmetricCryptographyService,
        'Asymmetric cryptography service object provided to digital envelope service');
  }
}
