/**
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.
*/
/**
 * @param {string} tag
 * @param {string} content
 * @param {number} offset
 * @returns {[number, number]} tag range start index, tag range length
 */
const getTagRange = (tag, content, offset) => {
  const tagStart = content.indexOf(`<${tag}`, offset);
  if (tagStart < 0) return [-1, 0];

  const tagEnd = content.indexOf('>', tagStart);
  return [tagStart, tagEnd - tagStart + 1];
};

module.exports = {
  /**
   * Retrieves the value of the provided attribute within the given tag.
   * @param {string} attribute
   * @param {string} tag
   * @return {string | void}
   */
  getAttribute(attribute, tag = '') {
    let attrStart = tag.indexOf(`${attribute}=`);
    if (attrStart === -1) return undefined;

    attrStart += attribute.length + 1;
    const quoteChar = tag[attrStart];
    if (quoteChar === ' ') return undefined;

    let attrEnd = -1;
    if (quoteChar === '"' || quoteChar === "'") {
      attrStart += 1;
      attrEnd = tag.indexOf(quoteChar, attrStart);
    } else {
      // handle unquoted <form method=post >
      attrEnd = tag.indexOf(' ', attrStart);

      // handle unquoted and last attribute <form method=post>
      if (attrEnd === -1) {
        attrEnd = tag[tag.length - 2] === '/' ? tag.length - 2 : tag.length - 1;
      }
    }

    return tag.substr(attrStart, attrEnd - attrStart);
  },

  /**
   * Find and return all of the requested opening tags within a section of HTML.
   * @param {string} tag
   * @param {string} content
   * @returns {string[]}
   */
  getElements(tag, content = '') {
    const elements = [];
    let offset = 0;
    let tagRangeStart = -1;
    let tagRangeLength = 0;

    do {
      [tagRangeStart, tagRangeLength] = getTagRange(tag, content, offset);
      if (tagRangeStart >= 0) {
        offset = tagRangeStart + tagRangeLength;
        elements.push(content.substr(tagRangeStart, tagRangeLength));
      }
    } while (tagRangeStart >= 0);

    return elements;
  }
};
