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

/**
 * Defines the digital envelope service.
 *
 * @namespace digitalenvelope
 */
cryptolib.modules.digitalenvelope.service = function(box) {
  'use strict';

  box.digitalenvelope = box.digitalenvelope || {};
  box.digitalenvelope.service = {};

  var digitalEnvelopeFactory;

  cryptolib('digitalenvelope', function(box) {
    digitalEnvelopeFactory =
        new box.digitalenvelope.factory.DigitalEnvelopeFactory();
  });

  /**
   * Creates a digital envelope, using one or more public keys, each of whose
   * corresponding private key can be used to open the envelope and retrieve
   * the data.
   *
   * @function createDigitalEnvelope
   * @param dataBase64
   *            {string} the data to store in the digital envelope, as a
   *            string in Base64 encoded format.
   * @param publicKeysPem
   *            {string[]} a list of one or more public keys used to generate
   *            the digital envelope, as an array of strings in PEM format.
   * @return {DigitalEnvelope} the newly created digital envelope.
   */
  box.digitalenvelope.service.createDigitalEnvelope = function(
      dataBase64, publicKeysPem) {

    var generator = digitalEnvelopeFactory.getDigitalEnvelopeGenerator();

    return generator.generate(dataBase64, publicKeysPem);
  };

  /**
   * Opens an existing digital envelope and retrieves the data that it
   * contains. The envelope can be opened with any private key corresponding
   * to a public key that was used to generate the envelope.
   *
   * @function openDigitalEnvelope
   * @param digitalEnvelope
   *            {DigitalEnvelope} the digital envelope to open.
   * @param privateKeyPem
   *            {string} the private key used to open the digital envelope, as
   *            a string in PEM format.
   * @return {string} the data contained in the digital envelope, as a string
   *         in Base64 encoded format.
   */
  box.digitalenvelope.service.openDigitalEnvelope = function(
      digitalEnvelope, privateKeyPem) {

    var opener = digitalEnvelopeFactory.getDigitalEnvelopeOpener();

    return opener.open(digitalEnvelope, privateKeyPem);
  };
};