import { StringFormatStrategy } from './string-format-strategy.abstract';
/**
 * A class for formatting string with the "," as the thousand separator
 *
 * @augments StringFormatStrategy
 */
export class ThousandCommaStrategy extends StringFormatStrategy {
  constructor(overrideValue = false) {
    super();
    this.overrideValue = overrideValue;
  }
  /**
   * If the input is a number, format it as a string
   *
   * @param {string} input - string
   * @returns {string} The input string, but with commas as thousands separator.
   */
  format(input) {
    if (!input.length)
      return input;
    const numValue = Number(input.replace(/,/g, ''));
    if (!isNaN(numValue) && numValue <= Number.MAX_SAFE_INTEGER) {
      return numValue.toLocaleString('en-US');
    }
    return input;
  }
  /**
   * Get the position of caret
   *
   * @param {string} input - The input string
   * @param {number} caretPosition - The current caret position
   * @returns {number} The new position of caret
   */
  calculateCaretPosition(input, caretPosition) {
    const formatInput = this.format(input);
    const oldFrontInput = input.substring(0, caretPosition);
    const newFrontInput = formatInput.substring(0, caretPosition);
    const oldFrontCommaCount = (oldFrontInput.match(/,/g) || []).length;
    const newFrontCommaCount = (newFrontInput.match(/,/g) || []).length;
    return caretPosition + (newFrontCommaCount - oldFrontCommaCount);
  }
}
