/**
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 { searchTimesF, searchTimesR } = require('./util');

const PLUS = '+';
const QUOTE_CHARS = ['`', "'", '"'];
const BACKTICK = QUOTE_CHARS[0];
const SINGLE = QUOTE_CHARS[1];

class Concatenations {
  constructor(str, opIdx) {
    this.string = str;
    this.operatorIdx = opIdx || str.indexOf(PLUS);
    this.reset();

    capture(this, str, this.operatorIdx);
  }

  /**
   * Resets the state of the current capture's concat info.
   */
  reset() {
    this.mergeable = false;
    this.left = { char: null, range: [-Infinity, -Infinity] };
    this.right = { char: null, range: [Infinity, Infinity] };
  }

  /**
   * Once <code>capture</code> has been called, this value
   * will return true or false based on whether an instance
   * of a concatenation has been found at the next index of
   * the '+' character. If not valid, we can search for the
   * next index of '+' and try again.
   */
  isValid() {
    return (
      this.mergeable &&
      [
        this.left.range.every(Number.isFinite),
        this.right.range.every(Number.isFinite)
      ].every(Boolean)
    );
  }

  /**
   * Merges the first occurrance of a string concatenation.
   */
  merge() {
    if (!this.isValid()) {
      return this.string;
    }

    const quote = resolveQuotes(this.left.char, this.right.char);

    const rangeL = [this.left.range[0] + 1, this.left.range[1]];
    const rangeR = [this.right.range[0] + 1, this.right.range[1]];

    const leftContents = this.string.substring(...rangeL);
    const rightContents = this.string.substring(...rangeR);

    this.lastIndex = this.right.range[1] - this.cutLength;

    this.string =
      this.string.substr(0, rangeL[0] - 1) +
      quote +
      leftContents +
      rightContents +
      quote +
      this.string.substr(rangeR[1] + 1);

    return this.string;
  }

  /**
   * Merges all occurrances of a string concatenation.
   */
  mergeAll() {
    this.merge();
    this.reset();
    this.operatorIdx = this.string.indexOf(PLUS, this.operatorIdx + 1);

    capture(this, this.string, this.operatorIdx);

    // Recurse while we still can find additional '+' operators.
    return 0 <= this.operatorIdx ? this.mergeAll() : this.string;
  }

  /**
   * Merges all occurrances of a string concatenation within the
   * provided string.
   */
  static clean(str) {
    return new Concatenations(str).mergeAll();
  }
}

/**
 * Captures the next string concatenation occurrence
 * within the instance's string value.
 * @param {} info
 * @param {} str
 * @param {} operatorIdx
 * @returns {}
 */
function capture(info, str, operatorIdx) {
  if (operatorIdx < 0) {
    return;
  }

  QUOTE_CHARS.reduce((memo, char) => {
    let range;

    /* Search for the first 2 quotes forwards from '+'  */
    range = searchTimesF(2, char, str, operatorIdx);
    if (!range.some((idx) => idx === -1)) {
      if (range[0] < memo.right.range[0]) {
        memo.right = { char, range };
      }
    }

    /* Search for the first 2 quotes backwards from '+' */
    range = searchTimesR(2, char, str, operatorIdx);
    if (!range.some((idx) => idx === -1)) {
      if (memo.left.range[1] < range[1]) {
        memo.left = { char, range };
      }
    }

    return memo;
  }, info);

  /* We've found something that looks like string concatenation;  */
  if (info.left.char && info.right.char) {
    const l = info.left.range[1] + 1;
    const r = info.right.range[0];

    /* ensure mergable - only '+' and spaces are between strings. */
    const operatorMatch = /(^[\r\n\s]*\+[\r\n\s]*$)/.exec(str.substr(l, r - l));

    if (operatorMatch) {
      /* We're removing inner quotes and what's between them.     */
      info.cutLength = operatorMatch[1].length + 2;
      info.mergeable = true;
    } else {
      info.mergeable = false;
    }
  }
}

/**
 * Resolves two quote strings to the one most appropriate
 * to perform the result of a concatenation. Backtick takes
 * highest rank, while single quote is default. If either
 * is <code>null</code>, then <code>null</code> is returned.
 * @param   {String}      char1 Quote character
 * @param   {String}      char2 Quote character
 * @returns {String|null}
 */
function resolveQuotes(char1, char2) {
  if (char1 === BACKTICK || char2 === BACKTICK) {
    return BACKTICK;
  } else if (char1 === null || char2 === null) {
    return null;
  } else {
    return SINGLE;
  }
}

module.exports = Concatenations;
