/**
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 ProtectionRuleActivity = require('./protection-rule-activity.js');
const RuleEvents = require('./rule-events.js');

/**
 * Activity reported for a specific attacker
 */
class AttackerActivity {
  constructor(source) {
    /**
     * @type {Source}
     */
    this.source = source;
    /**
     * @type {Object.<string,ProtectionRuleActivity>}
     */
    this.protectionRules = {};
    /**
     */
    this.virtualPatches = {};
  }

  /**
   * Add sample to the correct rule, with the correct status
   * @param {Object} data .ruleId, .status, .sample
   */
  addData(data) {
    // FIXME
    let activity;
    this.protectionRules[data.ruleId] = activity =
      this.protectionRules[data.ruleId] || new ProtectionRuleActivity();

    activity[data.status] = activity[data.status] || new RuleEvents();

    this.protectionRules[data.ruleId][data.status].addAttack(data.sample);
  }

  /**
   * Render the object so that it can be stringified and consumed by TeamServer
   */
  toSerializable() {
    return {
      source: this.source.toSerializable(),
      protectionRules: makeEachSerializable(this.protectionRules),
      virtualPatches: this.virtualPatches // TODO serialize
    };
  }
}

function makeEachSerializable(map) {
  const serializable = {};
  Object.entries(map).forEach(([key, value]) => {
    serializable[key] = value.toSerializable(); // from ProtectionRuleActivity
  });

  return serializable;
}

module.exports = AttackerActivity;
