/**
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 DOT = '.';

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

  /**
   * Converts substrings that look like JavaScript bracket
   * accessors (['abcd']) into dot accessor equivalents.
   */
  toDotNotation() {
    this.string = coerceToDotAccessors(this.string);
    return this.string;
  }

  /**
   * Cleans the given string value.
   * @param   {String} str the string to clean
   * @returns {String}
   */
  static clean(str) {
    return new Brackets(str).toDotNotation();
  }
}

/**
 * Coerces occurrences of substrings that look like
 * bracket accessors (['abcd'], ["efgh"]) into their
 * dot-accessor equivalents (.abcd, .efgh).
 * @param {} str
 * @returns {}
 */
function coerceToDotAccessors(str) {
  const startIdx = str.indexOf('[');
  if (-1 === startIdx) {
    return str;
  }

  const stopIdx = str.indexOf(']', startIdx + 1);
  if (-1 === stopIdx) {
    return str;
  }

  const bracketed = str.substring(startIdx, stopIdx + 1);
  const pattern = /^\[\s*[`'"]([a-zA-Z_]+[a-zA-Z0-9_]*)[`'"]\s*]$/;
  const match = pattern.exec(bracketed);

  return !match
    ? str
    : coerceToDotAccessors(
        [
          str.substr(0, startIdx),
          bracketToDot(bracketed),
          str.substr(stopIdx + 1)
        ].join('')
      );
}

/**
 * Turns a bracket-accessor string into a dot-accessor string.
 * @param   {String} bracket The string to convert
 * @returns {String}
 */
function bracketToDot(bracket) {
  bracket = bracket.replace(/\s/g, '');
  bracket = bracket.substring(2, bracket.length - 2);
  return `${DOT}${bracket}`;
}

module.exports = Brackets;
