/**
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 TagRange = require('../../models/tag-range');
const querystring = require('querystring');

/*
 * given a tag range return a new tag range that is
 *   1.  adjusted for position
 *   2.  adjusted for escaping
 */
module.exports.adjustRangeEscape = function adjustRangeEscape(
  tagRange,
  offset,
  str
) {
  const unescapedPrefix = str.slice(0, tagRange.start);
  const unescapedRange = str.slice(tagRange.start, tagRange.stop + 1);
  try {
    const escapedPrefixLength = querystring.escape(unescapedPrefix).length;
    const escapedRangeLength = querystring.escape(unescapedRange).length;
    return new TagRange(
      offset + escapedPrefixLength,
      offset + escapedPrefixLength + escapedRangeLength - 1,
      tagRange.tag
    );
  } catch (err) {
    // in general this shouldn't throw but it can if a tag range improperly
    // spans a surrogate pair
    // i.e. > querystring.escape('😐')
    // '%F0%9F%98%90'
    // > querystring.escape('😐'[0])
    // Uncaught URIError [ERR_INVALID_URI]: URI malformed
    return tagRange;
  }
};

module.exports.adjustRangeUnescape = function adjustRangeUnescape(
  tagRange,
  str,
  unescape = querystring.unescape
) {
  const escapedPrefix = str.slice(0, tagRange.start);
  const escapedRange = str.slice(tagRange.start, tagRange.stop + 1);
  try {
    const unescapedPrefixLength = unescape(escapedPrefix).length;
    const unescapedRangeLength = unescape(escapedRange).length;
    return new TagRange(
      unescapedPrefixLength,
      unescapedPrefixLength + unescapedRangeLength - 1,
      tagRange.tag
    );
  } catch (err) {
    return tagRange;
  }
};
