import {AnalyticalScope, Text} from "@webbpm/base-package";
import {ReplaceValueTextFormatter} from "./ReplaceValueTextFormatter";

@AnalyticalScope(Text)
export class PhoneNumberTextFormatter extends ReplaceValueTextFormatter {
  format(value: string): string {
    const newValue = super.format(value);
    if (newValue !== value) {
      return newValue;
    }
    return this.formatNumber(value);
  }
  private formatNumber(number: string): string {
    let cleanedNumber = number.replace(/\D/g, '');
    if (cleanedNumber.length === 11 && (cleanedNumber.startsWith('7') || cleanedNumber.startsWith('8'))) {
      cleanedNumber = cleanedNumber.slice(1)
      return cleanedNumber.replace(/^(\d{3})(\d{3})(\d{2})(\d{2})$/, '+7 ($1) $2-$3-$4');
    }
    return number;
  }
}