import { FeatureFlag } from '../../feature-control/feature-flag-controller';
import { CreditCardMaskStrategy } from './credit-card-mask-strategy.abstract';
/**
 * A class for formatting string with the given mask format
 *
 * @augments StringFormatStrategy
 */
export class CreditCardBlurMaskStrategy extends CreditCardMaskStrategy {
  /**
   * It creates a new instance of the Mask class.
   *
   * @param {boolean} hideCardNumberOnBlur - boolean
   */
  constructor(hideCardNumberOnBlur) {
    super({
      mask: '',
      slot: '9',
      accept: /[\d\s]/,
      insertMode: false,
      triggerAtInit: FeatureFlag.isEnabled('VEGA_INPUT_CREDIT_CARD.ENABLE_HIDE_NUMBER_MASK_ON_FIRST_LOAD'),
    });
    this.hideCardNumberOnBlur = hideCardNumberOnBlur;
  }
  /**
   * @inheritDoc
   */
  getCreditCardMaskConfig(value) {
    let maskConfig;
    const creditCardType = this.getCreditCardType(value);
    if (creditCardType) {
      if (this.hideCardNumberOnBlur && value.trim().includes(' ')) {
        maskConfig = this.generateDynamicMask(value);
      }
    }
    return maskConfig;
  }
  /*
   * The below method is e2e-test covered in
   *
   * @see{module:vega-input-credit-card-dynamic-mask-e2e}
   */
  /* istanbul ignore next */
  /**
   * Transform the input card number with dynamic card number mask, for example: '4111 2222 3333 44' will be transformed to 'XXXX XXXX XXXX 99'
   *
   * @param {string} value - card number string
   * @returns {MaskConfigType} - mask config type
   */
  generateDynamicMask(value) {
    const maskConfig = {
      type: 'custom',
      options: {
        mask: '',
        slot: '9',
        accept: /[\d\s]/,
        insertMode: false,
        triggerAtInit: FeatureFlag.isEnabled('VEGA_INPUT_CREDIT_CARD.ENABLE_HIDE_NUMBER_MASK_ON_FIRST_LOAD'),
      },
      trigger: 'blur',
    };
    const cardNumberSplit = value.trim().split(' ');
    const cardNumberMask = 
    // Map through the array and replace each character with 'X' or '9' depending on the index
    cardNumberSplit
      .map((element, index) => {
      // Replace each character in the string with 'X' except the last element, which uses '9'
      const replacementChar = index === cardNumberSplit.length - 1 ? '9' : 'X';
      return replacementChar.repeat(element.length);
    })
      .join(' ');
    maskConfig.options.mask = cardNumberMask;
    return maskConfig;
  }
}
