import { StringFormatStrategy } from './string-format-strategy.abstract';
import { isNonNullable } from '../../../types/type-guard';
/**
 * A class for formatting phone number with the given mask format
 *
 * @augments StringFormatStrategy
 */
export class VegaPhoneNumberInputStrategy extends StringFormatStrategy {
  constructor(formatter) {
    super();
    this.formatter = formatter;
  }
  /**
   * @inheritDoc
   */
  format(input) {
    return this.formatter(input);
  }
  /*
   * The below method is e2e-test covered in
   * module: Should show normal when phone number with same country code
   */
  /* istanbul ignore next */
  /**
   * Get the position of
   *
   * @param {string} input - The input string
   * @param {number} caretPosition - The current position of caret
   * @returns {Nullable<number>} The new position of caret
   */
  calculateCaretPosition(input, caretPosition) {
    if (isNonNullable(caretPosition)) {
      const startValue = input.substring(0, caretPosition);
      const numberCount = this.countNumbers(startValue);
      const maskedInputValue = this.format(input);
      const maskedStartValue = this.truncateToNumberCount(maskedInputValue, numberCount);
      if (maskedStartValue.length !== startValue.length &&
        !(maskedStartValue.endsWith(')') && maskedStartValue.slice(0, -1) === startValue)) {
        return caretPosition + (maskedStartValue.length - startValue.length);
      }
      else {
        return caretPosition;
      }
    }
  }
  /**
   * Trigger the formatter at init
   *
   * @returns {boolean} true or false
   */
  shouldTriggerAtInit() {
    return true;
  }
  /**
   * Count the numbers in a given string
   *
   * @param {string} value - given string
   * @returns {number} count
   */
  countNumbers(value) {
    let count = 0;
    for (let i = 0; i < value.length; i++) {
      const char = value[i];
      if (!isNaN(parseInt(char, 10)) && char !== ' ') {
        count++;
      }
    }
    return count;
  }
  /**
   * The below method is e2e-test covered in
   *
   * module:vega-input-phone-number-input-delete
   */
  /* istanbul ignore next */
  /**
   *
   * @param {string} value - a given string
   * @param {number} count - count of numbers
   * @returns {string} the return string
   */
  truncateToNumberCount(value, count) {
    let numberCount = 0;
    let result = '';
    if (count <= 0)
      return '';
    for (let i = 0; i < value.length; i++) {
      const char = value[i];
      if (/^\d$/.test(char)) {
        if (numberCount >= count) {
          break;
        }
        numberCount++;
        result += char;
      }
      else {
        if (numberCount < count || char === ')') {
          result += char;
        }
      }
    }
    return result;
  }
}
