/**
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 tagRangeUtil = require('../../models/tag-range/util');
const tracker = require('../../../tracker.js');

const { createEvent } = require('./utils');
const stackFactory = require('../../../core/stacktrace').singleton;

const urlParts = [
  'protocol',
  'auth',
  'host',
  'port',
  'hostname',
  'hash',
  'search',
  'query',
  'pathname',
  'path',
  'href'
];

module.exports.urlParts = urlParts;
module.exports.handle = handle;
module.exports.createTargetTagRanges = createTargetTagRanges;

function handle(data) {
  if (data.args.length < 1) {
    return;
  }

  const address = data.args[0];
  const sourceMetadata = tracker.getData(address);

  if (!sourceMetadata) {
    return;
  }

  propagate(sourceMetadata, address, data);
}

/**
 * Propagate data from address to url parts
 *
 * @param {ContrastProperties} sourceMetadata metadata from the source address
 * @param {string} address url.parse argument
 * @param {Url} url the 'this', ie the parsed url
 * @param {*[]}  args list of arguments passed to url.parse
 * @param {*} result the result of the call to url.parse
 */
function propagate(sourceMetadata, address, data) {
  const { obj: url, args, result } = data;

  let stack;

  for (const key of urlParts) {
    const part = url[key];

    if (part && typeof part === 'string' && part !== '') {
      const tracked = tracker.track(part);

      if (!tracked) {
        continue;
      }

      const { tagRanges: tags, event: sourceEvent } = sourceMetadata;

      const targetTagRanges = createTargetTagRanges({
        tags,
        address,
        part
      });
      if (targetTagRanges.length === 0) {
        continue;
      }

      // share stacks among events
      stack =
        stack ||
        stackFactory.createSnapshot({
          constructorOpt: data.hooked
        })();

      const event = createEvent(
        'Url.prototype.parse',
        stack,
        targetTagRanges,
        part,
        args,
        result
      );
      event.parents.push(sourceEvent);

      tracked.props.tagRanges = targetTagRanges;
      tracked.props.event = event;

      url[key] = tracked.str;
    }
  }
}

/**
 * Trim the tag ranges from the argument address to the url part
 * based on the indices of the part in the original address.
 *
 * @param {TagRange[]} tags
 * @param {string} address the address argument to url.parse()
 * @param {string} part the field in the parsed url object we are mapping to
 * @return {TagRange[]} trimmed tag ranges to go in the url object's field's metadata
 */
function createTargetTagRanges({ tags, address, part }) {
  const start = address.indexOf(part);
  if (start < 0) {
    return [];
  }

  const stop = start + part.length - 1;
  const trimmed = tagRangeUtil.trim(tags, start, stop);
  return trimmed;
}
