/*
 * 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 ZeroKnowledgeProofProver = require('../prover');
var ZeroKnowledgeProofVerifier = require('../verifier');
var ZeroKnowledgeProof = require('../proof');
var ZeroKnowledgeProofPreComputation = require('../pre-computation');
var PhiFunction = require('../phi-function');
var ProgressMeter = require('../progress-meter');
var validator = require('../input-validator');

module.exports = PlaintextProofHandler;

/**
 * @class PlaintextProofHandler
 * @classdesc Encapsulates a handler for the plaintext zero-knowledge proof of
 *            knowledge generation, pre-computation and verification processes.
 *            To instantiate this object, use the method {@link
 *            ZeroKnowledgeProofService.newPlaintextProofHandler}.
 * @param {ZpSubgroup}
 *            group The Zp subgroup to which all exponents and Zp group elements
 *            required for the proof generation are associated or belong,
 *            respectively.
 * @param {MessageDigestService}
 *            messageDigestService The message digest service.
 * @param {MathematicalService}
 *            mathService The mathematical service.
 */
function PlaintextProofHandler(group, messageDigestService, mathService) {
  var NUM_PHI_INPUTS = 1;
  var DEFAULT_AUXILIARY_DATA = 'PlaintextProof';

  var prover_ = new ZeroKnowledgeProofProver(messageDigestService, mathService);
  var verifier_ =
      new ZeroKnowledgeProofVerifier(messageDigestService, mathService);
  var mathGroupHandler_ = mathService.newGroupHandler();
  var progressCallback_;
  var progressPercentMinCheckInterval_;
  var measureProgress_ = false;

  var publicKey_;

  /**
   * Initializes the handler with the provided ElGamal public key.
   *
   * @function init
   * @memberof PlaintextProofHandler
   * @param {ElGamalPublicKey}
   *            publicKey The ElGamal public key.
   * @returns {PlaintextProofHandler} A reference to this object, to
   *          facilitate method chaining.
   * @throws {Error}
   *             If the input data validation fails.
   */
  this.init = function(publicKey) {
    validator.checkElGamalPublicKey(
        publicKey,
        'ElGamal public key for plaintext proof handler initialization', group);

    publicKey_ = publicKey;

    return this;
  };

  /**
   * Generates a plaintext zero-knowledge proof of knowledge. Before using
   * this method, the handler must have been initialized with a public key,
   * via the method {@link PlaintextProofHandler.init}.
   *
   * @function generate
   * @memberof PlaintextProofHandler
   * @param {Exponent}
   *            secret The secret exponent used to generate the ciphertext,
   *            the knowledge of which must be proven.
   * @param {ZpGroupElement[]}
   *            plaintext The plaintext from which the ciphertext was
   *            generated.
   * @param {ElGamalEncryptedElements}
   *            ciphertext The ciphertext.
   * @param {Object}
   *            [options] An object containing optional arguments.
   * @param {Uint8Array|string}
   *            [options.data='PlaintextProof'] Auxiliary data.
   * @param {ZeroKnowledgeProofPreComputation}
   *            [options.preComputation=Generated internally] A
   *            pre-computation of the plaintext zero-knowledge proof of
   *            knowledge.
   * @returns {ZeroKnowledgeProof} The plaintext zero-knowledge proof of
   *          knowledge.
   * @throws {Error}
   *             If the input data validation fails.
   */
  this.generate = function(secret, plaintext, ciphertext, options) {
    if (typeof publicKey_ === 'undefined') {
      throw new Error(
          'Cannot generate plaintext proof; Associated handler has not been initialized with any public key');
    }

    options = options || {};

    checkGenerationData(secret, plaintext, ciphertext, options);

    var data = options.data;
    if (typeof data === 'undefined') {
      data = DEFAULT_AUXILIARY_DATA;
    }

    var preComputation = options.preComputation;

    var privateValues = [secret];
    var publicValues = generatePublicValues(ciphertext, plaintext);
    if (typeof preComputation === 'undefined') {
      preComputation = this.preCompute();
    }

    return prover_.prove(
        group, privateValues, publicValues, data, preComputation);
  };

  /**
   * Pre-computes a plaintext zero-knowledge proof of knowledge. IMPORTANT:
   * The same pre-computed values must not be used twice. Before using this
   * method, the handler must have been initialized with a public key, via the
   * method {@link PlaintextProofHandler.init}.
   *
   * @function preCompute
   * @memberof PlaintextProofHandler
   * @returns {ZeroKnowledgeProofPreComputation} The plaintext zero-knowledge
   *          proof of knowledge pre-computation.
   */
  this.preCompute = function() {
    if (typeof publicKey_ === 'undefined') {
      throw new Error(
          'Cannot pre-compute plaintext proof; Associated handler has not been initialized with any public key');
    }

    var phiFunction = newPhiFunction(publicKey_);

    if (!measureProgress_) {
      return prover_.preCompute(group, phiFunction);
    } else {
      var preComputation =
          prover_.preCompute(group, phiFunction, newProgressMeter(publicKey_));
      measureProgress_ = false;

      return preComputation;
    }
  };

  /**
   * Verifies a plaintext zero-knowledge proof of knowledge. Before using this
   * method, the handler must have been initialized with a public key, via the
   * method {@link PlaintextProofHandler.init}.
   *
   * @function verify
   * @memberof PlaintextProofHandler
   * @param {ZeroKnowledgeProof}
   *            proof The plaintext zero-knowledge proof of knowledge to
   *            verify.
   * @param {ZpGroupElement[]}
   *            plaintext The plaintext from which the ciphertext was
   *            generated.
   * @param {ElGamalEncryptedElements}
   *            ciphertext The ciphertext.
   * @param {Object}
   *            [options] An object containing optional arguments.
   * @param {Uint8Array|string}
   *            [options.data='PlaintextProof'] Auxiliary data. It must be the
   *            same as that used to generate the proof.
   * @returns {boolean} <code>true</code> if the plaintext zero-knowledge
   *          proof of knowledge was verified, <code>false</code> otherwise.
   * @throws {Error}
   *             If the input data validation fails.
   */
  this.verify = function(proof, plaintext, ciphertext, options) {
    if (typeof publicKey_ === 'undefined') {
      throw new Error(
          'Cannot verify plaintext proof; Associated handler has not been initialized with any public key');
    }

    options = options || {};

    checkVerificationData(proof, plaintext, ciphertext, options);

    var data = options.data;
    if (typeof data === 'undefined') {
      data = DEFAULT_AUXILIARY_DATA;
    }

    var phiFunction = newPhiFunction(publicKey_);
    var publicValues = generatePublicValues(ciphertext, plaintext);

    if (!measureProgress_) {
      return verifier_.verify(group, proof, phiFunction, publicValues, data);
    } else {
      var verified = verifier_.verify(
          group, proof, phiFunction, publicValues, data,
          newProgressMeter(publicKey_));
      measureProgress_ = false;

      return verified;
    }
  };

  /**
   * Indicates that a progress meter is to be used for the next plaintext
   * zero-knowledge proof of knowledge operation to be performed.
   *
   * @function measureProgress
   * @memberof PlaintextProofHandler
   * @param {function}
   *            callback The callback function for the progress meter.
   * @param {Object}
   *            [options] An object containing optional arguments.
   * @param {number}
   *            [minCheckInterval=10] The minimum interval used to check
   *            progress, as a percentage of the expected final progress
   *            value.
   * @returns {PlaintextProofHandler} A reference to this object, to
   *          facilitate method chaining.
   * @throws {Error}
   *             If the input data validation fails.
   */
  this.measureProgress = function(callback, minCheckInterval) {
    validator.checkProgressMeterData(
        callback, minCheckInterval, 'Plaintext zero-knowledge proof');

    progressCallback_ = callback;
    progressPercentMinCheckInterval_ = minCheckInterval;

    measureProgress_ = true;

    return this;
  };

  function generatePublicValues(ciphertext, plaintext) {
    var quotientElements =
        mathGroupHandler_.divideElements(ciphertext.phis, plaintext);

    return [ciphertext.gamma].concat(quotientElements);
  }

  function newPhiFunction(publicKey) {
    var numOutputs = publicKey.elements.length + 1;
    var computationRules = generateComputationRules(numOutputs);
    var baseElements = generateBaseElements(publicKey);

    return new PhiFunction(
        NUM_PHI_INPUTS, numOutputs, computationRules, baseElements);
  }

  function generateComputationRules(numOutputs) {
    var rules = [];

    for (var i = 0; i < numOutputs; i++) {
      rules[i] = [];
      rules[i][0] = [];
      rules[i][0].push(i + 1);
      rules[i][0].push(1);
    }

    return rules;
  }

  function generateBaseElements(publicKey) {
    return [group.generator].concat(publicKey.elements);
  }

  function newProgressMeter(publicKey) {
    var progressMax = publicKey.elements.length + 1;

    return new ProgressMeter(
        progressMax, progressCallback_, progressPercentMinCheckInterval_);
  }

  function checkGenerationData(secret, plaintext, ciphertext, options) {
    validator.checkExponent(
        secret, 'Secret exponent for plaintext proof generation', group.q);
    validator.checkZpGroupElements(
        plaintext, 'Plaintext Zp group elements for plaintext proof generation',
        group);
    validator.checkElGamalEncryptedElements(
        ciphertext,
        'Ciphertext ElGamal encrypted Zp group elements for plaintext proof generation',
        group);
    validator.checkArrayLengthsEqual(
        plaintext, 'plaintext Zp group elements for plaintext proof generation',
        publicKey_.elements, 'ElGamal public key Zp group elements');
    validator.checkArrayLengthsEqual(
        ciphertext.phis,
        'Ciphertext ElGamal phi Zp group elements for plaintext proof generation',
        publicKey_.elements, 'ElGamal public key Zp group elements');
    if (typeof options.data !== 'undefined' &&
        typeof options.data !== 'string') {
        validator.checkIsInstanceOf(
            options.data, Uint8Array, 'Uint8Array',
            'Non-string auxiliary data for plaintext proof generation');
    }
    if (typeof options.preComputation !== 'undefined') {
      validator.checkIsInstanceOf(
          options.preComputation, ZeroKnowledgeProofPreComputation,
          'ZeroKnowledgeProofPreComputation',
          'Pre-computation for plaintext proof generation');
    }
  }

  function checkVerificationData(proof, plaintext, ciphertext, options) {
    validator.checkIsInstanceOf(
        proof, ZeroKnowledgeProof, 'ZeroKnowledgeProof',
        'Plaintext zero-knowledge proof');
    validator.checkZpGroupElements(
        plaintext,
        'Plaintext Zp group elements for plaintext proof verification', group);
    validator.checkElGamalEncryptedElements(
        ciphertext,
        'Ciphertext ElGamal encrypted elements for plaintext proof verification',
        group);
    validator.checkArrayLengthsEqual(
        plaintext,
        'plaintext Zp group elements for plaintext proof verification',
        publicKey_.elements, 'ElGamal public key Zp group elements');
    validator.checkArrayLengthsEqual(
        ciphertext.phis,
        'Ciphertext Elgamal phi Zp group elements for plaintext proof verification',
        publicKey_.elements, 'ElGamal public key Zp group elements');
    if (typeof options.data !== 'undefined' &&
        typeof options.data !== 'string') {
        validator.checkIsInstanceOf(
            options.data, Uint8Array, 'Uint8Array',
            'Non-string auxiliary data for plaintext proof verification');
    }
  }
}
