/**
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 agentEmitter = require('../../agent-emitter');
const { EVENT_TYPES } = require('../../constants');
const BaseEvent = require('./base-event');

module.exports = class PropagationEvent extends BaseEvent {
  /**
   * Create a propagation event.
   * @param {Object}       opts
   * @param {CallContext}  opts.context
   * @param {BaseEvent[]=} opts.parents
   * @param {Signature}    opts.signature
   * @param {string}       opts.source
   * @param {TagRange[]}   opts.tagRanges
   * @param {string[]}     opts.tags
   * @param {string}       opts.target
   * @param {string[]}     opts.untags
   */
  constructor({
    context,
    parents = [],
    signature,
    source,
    tagRanges,
    tags,
    target,
    untags
  } = {}) {
    super(context, signature, tagRanges);
    this.source = source;
    this.target = target;

    // these do not get serialized, they just help us give this the proper type
    // and could be used for something later
    if (Array.isArray(tags) && tags.length === 0) {
      tags = undefined;
    }
    if (Array.isArray(untags) && untags.length === 0) {
      untags = undefined;
    }
    this.tags = tags;
    this.untags = untags;

    this.parents = parents;

    agentEmitter.emit('dataflowEvent', this);
  }

  get action() {
    if (this.tags || this.untags) {
      return 'TAG';
    }

    const source = this.source ? this.source[0] : '?';
    const target = this.target ? this.target[0] : '?';
    return `${source}2${target}`;
  }

  get type() {
    return this.tags || this.untags ? EVENT_TYPES.TAG : EVENT_TYPES.PROPAGATION;
  }
};
