import { NumberMaskStrategy } from './number-mask-strategy';
/**
 * A class for formatting number string with the "," as the thousand separator
 */
export class NumberThousandCommaStrategy extends NumberMaskStrategy {
  /**
   * It creates a new instance of the Mask class.
   *
   * @param {NumberMaskConfig} maskConfig - MaskConfig
   * @param {boolean} overrideValue - Whether to override the value after blur, default is false
   */
  constructor(maskConfig, overrideValue = false) {
    super(maskConfig, overrideValue);
  }
  /**
   * If the input is a number, format it as a thousand comma string
   *
   * @param {string} input - string
   * @returns {string} The input string, but with commas as thousands separator.
   */
  format(input) {
    const redressedInput = this.redressAbnormalNumber(input);
    if (this.skipFormat(redressedInput)) {
      return redressedInput;
    }
    const resultStringBuilder = [...redressedInput];
    for (let i = redressedInput.length - 1; i >= 0; i--) {
      const value = resultStringBuilder.join('');
      if (this.inputNeedFormat(value.replace(/,/g, ''))) {
        resultStringBuilder.pop();
      }
    }
    return this.thousandCommaFormat(resultStringBuilder.join(''));
  }
  /**
   * 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 redressedInput = this.redressAbnormalNumber(input);
    const formattedInput = this.format(input);
    const oldFrontInput = input.substring(0, caretPosition);
    const newFrontInput = formattedInput.substring(0, caretPosition);
    const oldFrontCommaCount = (oldFrontInput.match(/,/g) || []).length;
    const newFrontCommaCount = (newFrontInput.match(/,/g) || []).length;
    return (caretPosition + (newFrontCommaCount - oldFrontCommaCount) - (input.length - redressedInput.length));
  }
  /**
   * The function `thousandCommaFormat` takes a string input, removes non-numeric characters, formats the number with thousand commas, and returns the result.
   *
   * @param {string} input - Takes a string input and formats it by adding commas to separate thousands. It also handles decimal values based on the precision specified in the `maskConfig`.
   * @returns {string} Returns a formatted string with commas for thousands separator and optional decimal places.
   */
  thousandCommaFormat(input) {
    if (!input.length)
      return input;
    const inputValue = input.replace(/[^\d.-]/g, '');
    const pointIndex = inputValue.indexOf('.');
    const decimals = inputValue.length > 1 && pointIndex >= 1 ? inputValue.slice(pointIndex) : '';
    const numValue = Number(inputValue.split('.')[0]);
    if (!isNaN(numValue) && numValue <= Number.MAX_SAFE_INTEGER) {
      return numValue.toLocaleString('en-US') + decimals;
    }
    else {
      return inputValue;
    }
  }
}
