/*
 * 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 codec = require('scytl-codec');

module.exports = DigitalEnvelope;

/**
 * @class DigitalEnvelope
 * @classdesc Encapsulates a digital envelope. This object is instantiated by
 *            the method {@link DigitalEnvelopeService.newEnvelope} or
 *            internally by the method {@link
 *            DigitalEnvelopeGenerator.generate}.
 * @property {Uint8Array} encryptedData The symmetrically encrypted data.
 * @property {Uint8Array} mac The MAC of the symmetrically encrypted data.
 * @property {EncryptedSecretKeyPair[]} encryptedSecretKeyPairs The asymmetric
 *           encryptions of the concatenation of the encryption secret key and
 *           MAC secret key used to generate and open the digital envelope, each
 *           asymmetric encryption having been generated using a different one
 *           of the public keys used to initialize digital envelope generator.
 */
function DigitalEnvelope(encryptedData, mac, encryptedSecretKeyPairs) {
  this.encryptedData = encryptedData;
  this.mac = mac;
  Object.freeze(this.encryptedSecretKeyPairs = encryptedSecretKeyPairs);

  Object.freeze(this);
}

DigitalEnvelope.prototype = {
  /**
   * Serializes this object into a JSON string representation.
   * <p>
   * <b>IMPORTANT:</b> This serialization must be exactly the same as the
   * corresponding serialization in the library <code>cryptoLib</code>,
   * implemented in Java, since the two libraries are expected to communicate
   * with each other via these serializations.
   * <p>
   *
   * @function toJson
   * @memberof DigitalEnvelope
   * @returns {string} The JSON string representation of this object.
   */
  toJson: function() {
    var encryptedDataB64 = codec.base64Encode(this.encryptedData);
    var macB64 = codec.base64Encode(this.mac);
    var encryptedSecretKeyPairs = this.encryptedSecretKeyPairs;

    var encryptedSecretKeyPairsB64 = [];
    var publicKeysPem_ = [];
    for (var i = 0; i < encryptedSecretKeyPairs.length; i++) {
      encryptedSecretKeyPairsB64.push(
          codec.base64Encode(encryptedSecretKeyPairs[i].encryptedKeyPair));
      publicKeysPem_[i] = encryptedSecretKeyPairs[i].publicKey;
    }

    return JSON.stringify({
      digitalEnvelope: {
        encryptedDataBase64: encryptedDataB64,
        macBase64: macB64,
        encryptedSecretKeyConcatsBase64: encryptedSecretKeyPairsB64,
        publicKeysPem: publicKeysPem_
      }
    });
  }
};
