/**
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.
*/
/**
 * @module
 */
'use strict';

const Source = require('./source.js');
const AttackerActivity = require('./attacker-activity.js');

/** Holds defend data for AppActivity messages */
class Defend {
  constructor(settings) {
    settings = settings || {};

    /**
     * @type {Object}
     * Holds counts of attack events by status.
     */
    this.attackCounts = {
      blocked: 0,
      blockedAtPerimeter: 0,
      exploited: 0,
      ineffective: 0
    };

    /**
     * @type {Array.AttackerActivity}
     * XXX maybe could this be a Map to prevent logic in addAttack?
     */
    this.attackers = [];
  }

  /**
   * Adds an attack finding to the collection. If an attacker is found
   * Who's source info matches the finding, the finding will be appended
   * to that attacker's data set.
   * @param   {Object} data
   * @param   {String} data.ruleId
   * @param   {Sample} data.sample
   * @param   {String} data.status
   * @returns {}
   */
  addAttack(finding) {
    this.attackCounts[finding.status] += 1;
    const source = new Source(finding.sample.request);
    const knownAttacker = this.attackers.some((attackerActivity) => {
      if (source.equals(attackerActivity.source)) {
        attackerActivity.addData(finding);
        return true;
      }
      return false;
    });

    if (!knownAttacker) {
      const attackerActivity = new AttackerActivity(source);
      attackerActivity.addData(finding);
      this.attackers.push(attackerActivity);
    }
  }

  /**
   * Render the object so that it can be stringified and consumed by TeamServer
   */
  toSerializable() {
    return {
      attackers: this.attackers.map((attacker) => attacker.toSerializable())
    };
  }

  /**
   * Look in the list of attackers and return the source of the attacker
   * if it matches the provided source. Otherwise return ~null~.
   * @param {AttackerActivity[]} attackers Attackers to search
   * @param {Source}             source    Source to use for comparison
   */
  static findSource(attackers, source) {
    return attackers.find((a) => a.source.equals(source)) || null;
  }
}

module.exports = Defend;
