/**
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 logger = require('../../../core/logger')('contrast:protect:signatures');
const Evaluator = require('./evaluator');

class SignatureKit extends Map {
  /**
   * @param {Object[]} definitions Keywords and patterns for all rules
   */
  constructor(definitions) {
    // Make definitions into enumerable instances
    super(configure(definitions));
  }

  static setEvaluator(signature) {
    if (!signature.evaluator) {
      signature.evaluator = new Evaluator(signature);
    }
    return signature;
  }

  static setCustomSearchers(signature) {
    if (!signature.customSearchers) {
      signature.customSearchers = [];
    }
    return signature;
  }

  static setDefaultThresholds(signature) {
    if (!signature.watchThreshold) {
      signature.watchThreshold = Infinity;
    }
    if (!signature.definiteThreshold) {
      signature.definiteThreshold = Infinity;
    }

    return signature;
  }
}

module.exports = SignatureKit;
module.exports.configure = configure;

/**
 * Given a rule definition list configuration, the instance builds
 * its set of signatures from the local constructors.
 * Each signature becomes accessible by name on the instance.
 * @param {Object[]} definitions Keywords and patterns for all rules
 */
function configure(definitions = []) {
  return definitions.map((def) => {
    let signature, Ctor;
    try {
      const sigPath = `./${def.name}`;
      Ctor = require(sigPath);
      signature = new Ctor(def);
    } catch (e) {
      logger.debug(`Signature CreationError "${def.name}" - ${e.message}`);
      return [];
    }

    signature = new Ctor(def);
    SignatureKit.setEvaluator(signature);
    SignatureKit.setCustomSearchers(signature);
    SignatureKit.setDefaultThresholds(signature);

    return [def.name, signature];
  });
}
