/*
 * 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';

module.exports = ProgressMeter;

/**
 * @class ProgressMeter
 * @classdesc Encapsulates a progress meter for zero-knowledge proof of
 *            knowledge generation, pre-computation or verification. it
 *            is instantiated internally by the proof handlers.
 * @private
 * @param {number}
 *            progressMax The maximum amount of progress to be attained.
 * @param {function}
 *            callback The progress meter callback function.
 * @param {number}
 *            [minCheckInterval=10] The minimum check interval of the progress,
 *            as a percentage of the expected final progress value.
 */
function ProgressMeter(progressMax, callback, minCheckInterval) {
  var minCheckInterval_ = minCheckInterval || 10;
  var lastProgressPercent_ = 0;

  /**
   * Calculates the progress as a percentage of the expected final value and
   * provides it as input to the provided callback function.
   *
   * @function update
   * @memberof ProgressMeter
   * @param {number}
   *            progress The present amount of progress.
   */
  this.update = function(progress) {
    if (callback === undefined) {
      return;
    }

    var progressPercent = Math.floor((progress / progressMax) * 100);
    progressPercent = Math.min(progressPercent, 100);

    var progressPercentChange = progressPercent - lastProgressPercent_;

    if (progressPercentChange > 0) {
      var checkProgress = (progressPercentChange >= minCheckInterval_) ||
          (progressPercent === 100);
      if (checkProgress) {
        lastProgressPercent_ = progressPercent;
        callback(progressPercent);
      }
    }
  };

  /**
   * Resest the progress meter.
   *
   * @function reset
   * @memberof ProgressMeter
   */
  this.reset = function() {
    lastProgressPercent_ = 0;
  };
}
