/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

const UserInputEvaluator = require('../../../util/user-input-evaluator');

/**
 * This builds the object that we use to capture input matches between
 * <code>prefilter</code> method calls. We need to do this because we
 * recieve different parts of the request individually as the source
 * provider emits each event e.g. <code>request.headersParsed</code>.
 * @param   {Object} dtm A VirtualPatch DTM
 * @returns {Object}       The dtm conditions put into an array and
 *                         partitioned into <code>met</code> and
 *                         <code>unmet</code> collections.
 */
function getConditions(dtm) {
  return dtm.conditionsList.map((condition) => {
    condition.input = condition.inputType.toLowerCase();
    return condition;
  });
}

function getEvaluators(conditions) {
  return conditions.map((c) => UserInputEvaluator.create(c));
}

/**
 * @param {} conditions
 */
function getApplicableInputs(conditions) {
  return conditions.reduce((inputs, condition) => {
    inputs[condition.inputType] = true;
    return inputs;
  }, {});
}

/**
 * Evaluates all user inputs against all conditions.
 * If an evaluation passes is met, its evaluator is removed
 * from the set.
 *
 * @param   {Condition[]} conditions
 * @param   {UserInput[]} userInputs UserInput DTMs
 * @returns {Object}                 The new conditions
 */
function evaluate(evaluators, input) {
  for (const evaluator of evaluators) {
    if (evaluator(input)) {
      evaluators.delete(evaluator);
    }
  }
}

module.exports = {
  evaluate,
  getApplicableInputs,
  getConditions,
  getEvaluators
};
