/**
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 os = require('os');
const BLOCK = { START: '/*', END: '*/' };
const INLINE = { START: '//', END: os.EOL };

class Comments {
  constructor(str) {
    this.string = str;
  }

  /**
   * Removes all comments from the instance's string value.
   * Searches for both block and inline comments and determines
   * how to remove them.
   */
  remove() {
    const blockStart = this.string.indexOf(BLOCK.START);
    const blockEnd = this.string.indexOf(BLOCK.END, blockStart);

    const inlineStart = this.string.indexOf(INLINE.START);
    const inlineEnd = this.string.indexOf(INLINE.END, inlineStart);

    const activeRange = resolveRanges(
      [blockStart, blockEnd],
      [inlineStart, inlineEnd]
    );

    if (activeRange) {
      const offset = activeRange[1] == blockEnd ? 2 : 1;

      this.string = [
        this.string.substring(0, activeRange[0]),
        this.string.substring(activeRange[1] + offset)
      ].join('');

      this.remove();
    }

    return this.string;
  }

  /**
   * Static method to clean all comments from a string.
   * @param {} str
   * @returns {}
   */
  static clean(str) {
    return new Comments(str).remove();
  }
}

/**
 * Takes a block comment range and an inline comment range and compares
 * them do determine which is the appropriate one to remove from the string.
 * @param   {Number[]}      range1 Range of indices of found block comment
 * @param   {Number[]}      range2 Range of indices of found inline comment
 * @returns {Number[]|null}
 */
function resolveRanges(block, inline) {
  const blockValid = isRangeValid(block);
  const inlineValid = isRangeValid(inline);

  /* Cases where one or both ranges are invalid: */
  if (!blockValid && !inlineValid) {
    return null;
  }
  if (blockValid && !inlineValid) {
    return block;
  }
  if (!blockValid && inlineValid) {
    return inline;
  }

  /* Both are valid, so we need to look at arrangement. */
  return block[0] < inline[0] ? block : inline;
}

/**
 * Whether the given range is a valid set if indices.
 * @param   {Number[]} range
 * @returns {Boolean}
 */
function isRangeValid(range) {
  return (
    range &&
    range.length === 2 &&
    range[0] < range[1] &&
    -1 < range[0] &&
    -1 < range[1]
  );
}

module.exports = Comments;
