/**
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 tracker = require('../../tracker');
const { PropagationEvent, Signature, CallContext } = require('../models');
const tagRangeUtil = require('../models/tag-range/util');

module.exports.handle = handle;

const signature = new Signature('String.prototype.trim');

function handle(data) {
  const { obj, result } = data;
  const sourceMetadata = tracker.getData(obj);
  if (!sourceMetadata) {
    return;
  }

  if (result.length === 0) {
    return;
  }

  const left = obj.indexOf(result);
  const right = left + result.length - 1;
  const { tagRanges: sourceTagRanges, event: sourceEvent } = sourceMetadata;
  const targetRanges = tagRangeUtil.trim(sourceTagRanges, left, right);

  if (targetRanges.length === 0) {
    return;
  }

  const tracked = tracker.track(result);
  if (tracked) {
    tracked.props.tagRanges = targetRanges;
    const context = CallContext.create(data);
    const event = new PropagationEvent({
      context,
      signature,
      tagRanges: targetRanges,
      source: 'O',
      target: 'R'
    });
    event.parents.push(sourceEvent);
    tracked.props.event = event;

    data.result = tracked.str;
  }
}
