/*
 * 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 = SchnorrProofHandler;

/**
 * @class SchnorrProofHandler
 * @classdesc Encapsulates a handler for the Schnorr zero-knowledge proof of
 *            knowledge generation, pre-computation and verification processes.
 *            To instantiate this object, use the method {@link
 *            ZeroKnowledgeProofService.newSchnorrProofHandler}.
 * @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}
 *            mathematicalService The mathematical service.
 */
function SchnorrProofHandler(group, messageDigestService, mathematicalService) {
  var NUM_PHI_INPUTS = 1;
  var NUM_PHI_OUTPUTS = 1;
  var COMPUTATION_RULES = [[[1, 1]]];
  var DEFAULT_AUXILIARY_DATA = 'SchnorrProof';
  var VOTER_ID_PREFIX = 'SchnorrProof:VoterID=';
  var ELECTION_ID_PREFIX = 'ElectionEventID=';

  var prover_ =
      new ZeroKnowledgeProofProver(messageDigestService, mathematicalService);
  var verifier_ =
      new ZeroKnowledgeProofVerifier(messageDigestService, mathematicalService);
  var progressCallback_;
  var progressPercentMinCheckInterval_;
  var measureProgress_ = false;

  /**
   * Generates a Schnorr zero-knowledge proof of knowledge.
   *
   * @function generate
   * @memberof SchnorrProofHandler
   * @param {Exponent}
   *            secret The secret exponent used to generate the gamma element,
   *            the knowledge of which must be proven
   * @param {ZpGroupElement}
   *            gamma The Zp subgroup generator exponentiated to the secret
   *            exponent.
   * @param {Object}
   *            [options] An object containing optional arguments.
   * @param {Uint8Array|string}
   *            [options.data=''] Auxiliary data.
   * @param {ZeroKnowledgeProofPreComputation}
   *            [options.preComputation=Generated internally] A
   *            pre-computation of the Schnorr zero-knowledge proof of
   *            knowledge.
   * @param {string}
   *            [options.voterId] The voter ID. If this value is set then the
   *            <code>electionId</code> option must also be set. In this
   *            case, the <code>data</code> parameter will be ignored.
   * @param {string}
   *            [options.electionId] The election ID. If this value is set
   *            then the <code>voterId</code> option must also be set. In
   *            this case, the <code>data</code> parameter will be ignored.
   * @returns {ZeroKnowledgeProof} The Schnorr zero-knowledge proof of
   *          knowledge.
   * @throws {Error}
   *             If the input data validation fails.
   */
  this.generate = function(secret, gamma, options) {
    options = options || {};

    checkGenerationData(secret, gamma, options);

    var data = options.data;
    if (typeof data === 'undefined') {
      data = DEFAULT_AUXILIARY_DATA;
    }
    var voterId = options.voterId;
    var electionId = options.electionId;
    if (voterId && electionId) {
      data = VOTER_ID_PREFIX + voterId + ELECTION_ID_PREFIX + electionId;
    }
    var preComputation = options.preComputation;

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

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

  /**
   * Pre-computes a Schnorr zero-knowledge proof of knowledge. IMPORTANT: The
   * same pre-computed values must not be used twice.
   *
   * @function preCompute
   * @memberof SchnorrProofHandler
   * @returns {ZeroKnowledgeProofPreComputation} The Schnorr zero-knowledge
   *          proof of knowledge pre-computation.
   */
  this.preCompute = function() {
    var phiFunction = newPhiFunction(group);

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

      return preComputation;
    }
  };

  /**
   * Verifies a Schnorr zero-knowledge proof of knowledge.
   *
   * @function verify
   * @memberof SchnorrProofHandler
   * @param {ZeroKnowledgeProof}
   *            proof The Schnorr zero-knowledge proof of knowledge to verify.
   * @param {ZpGroupElement}
   *            gamma The Zp subgroup generator exponentiated to the secret
   *            exponent, the knowledge of which must be verified.
   * @param {Object}
   *            [options] An object containing optional arguments.
   * @param {Uint8Array|string}
   *            [options.data=''] Auxiliary data. It must be the same as that
   *            used to generate the proof.
   * @returns {boolean} <code>true</code> if the Schnorr zero-knowledge
   *          proof of knowledge was verified, <code>false</code> otherwise.
   * @throws {Error}
   *             If the input data validation fails.
   */
  this.verify = function(proof, gamma, options) {
    options = options || {};

    checkVerificationData(proof, gamma, options);

    var data = options.data;
    if (typeof data === 'undefined') {
      data = DEFAULT_AUXILIARY_DATA;
    }
    var voterId = options.voterId;
    var electionId = options.electionId;
    if (voterId && electionId) {
      data = VOTER_ID_PREFIX + voterId + ELECTION_ID_PREFIX + electionId;
    }

    var phiFunction = newPhiFunction(group);
    var publicValues = [gamma];

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

      return verified;
    }
  };

  /**
   * Indicates that a progress meter is to be used for the next Schnorr
   * zero-knowledge proof of knowledge operation to be performed.
   *
   * @function measureProgress
   * @memberof SchnorrProofHandler
   * @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 {SchnorrProofHandler} 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, 'Schnorr zero-knowledge proof');

    progressCallback_ = callback;
    progressPercentMinCheckInterval_ = minCheckInterval;

    measureProgress_ = true;

    return this;
  };

  function newPhiFunction(group) {
    var baseElements = [group.generator];

    return new PhiFunction(
        NUM_PHI_INPUTS, NUM_PHI_OUTPUTS, COMPUTATION_RULES, baseElements);
  }

  function newProgressMeter() {
    return new ProgressMeter(
        NUM_PHI_OUTPUTS, progressCallback_, progressPercentMinCheckInterval_);
  }

  function checkGenerationData(secret, gamma, options) {
    validator.checkExponent(
        secret, 'Secret exponent for Schnorr proof generation', group.q);
    validator.checkZpGroupElement(
        gamma, 'ElGamal gamma Zp group element for Schnorr proof generation',
        group);
    if (typeof options.data !== 'undefined' &&
        typeof options.data !== 'string') {
        validator.checkIsInstanceOf(
            options.data, Uint8Array, 'Uint8Array',
            'Non-string auxiliary data for Schnorr proof generation');
    }
    if (typeof options.voterId !== 'undefined') {
      validator.checkIsNonEmptyString(
          options.voterId, 'Voter ID for Schnorr proof generation');
      if (typeof options.electionId === 'undefined') {
        throw new Error(
            'Voter ID was provided but no election ID was provided for Schnorr proof generation');
      }
    }
    if (typeof options.electionId !== 'undefined') {
      validator.checkIsNonEmptyString(
          options.electionId, 'Election ID for Schnorr proof generation');
      if (typeof options.voterId === 'undefined') {
        throw new Error(
            'Election ID was provided but no voter ID was provided for Schnorr proof generation');
      }
    }
    if (typeof options.preComputation !== 'undefined') {
      validator.checkIsInstanceOf(
          options.preComputation, ZeroKnowledgeProofPreComputation,
          'ZeroKnowledgeProofPreComputation',
          'Pre-computation for Schnorr proof generation');
    }
  }

  function checkVerificationData(proof, gamma, options) {
    validator.checkIsInstanceOf(
        proof, ZeroKnowledgeProof, 'ZeroKnowledgeProof',
        'Schnorr zero-knowledge proof');
    validator.checkZpGroupElement(
        gamma, 'ElGamal gamma Zp group element for Schnorr proof verification',
        group);
    if (typeof options.data !== 'undefined' &&
        typeof options.data !== 'string') {
        validator.checkIsInstanceOf(
            options.data, Uint8Array, 'Uint8Array',
            'Non-string auxiliary data for Schnorr proof verification');
    }
    if (typeof options.voterId !== 'undefined') {
      validator.checkIsNonEmptyString(
          options.voterId, 'Voter ID for Schnorr proof verification');
      if (typeof options.electionId === 'undefined') {
        throw new Error(
            'Voter ID was provided but no election ID was provided for Schnorr proof verification');
      }
    }
    if (typeof options.electionId !== 'undefined') {
      validator.checkIsNonEmptyString(
          options.electionId, 'Election ID for Schnorr proof verification');
      if (typeof options.voterId === 'undefined') {
        throw new Error(
            'Election ID was provided but no voter ID was provided for Schnorr proof verification');
      }
    }
  }
}
