import {NotNull, TextFormatter, Visible} from "@webbpm/base-package";

// A text formatter for integer values appending a prefix and/or suffix
// depending on the last digit of the value
export class NumberPrefixSuffixTextFormatter implements TextFormatter {

  @NotNull()
  public hasPrefix: boolean;

  @Visible("hasPrefix == true")
  @NotNull("hasPrefix == true")
  public oneDigitPrefix: string;
  @Visible("hasPrefix == true")
  @NotNull("hasPrefix == true")
  public otherDigitPrefix: string;

  @NotNull()
  public hasSuffix: boolean;

  @Visible("hasSuffix == true")
  @NotNull("hasSuffix == true")
  public oneDigitSuffix: string;
  @Visible("hasSuffix == true")
  @NotNull("hasSuffix == true")
  public fromTwoToFourDigitSuffix: string;
  @Visible("hasSuffix == true")
  @NotNull("hasSuffix == true")
  public otherDigitSuffix: string;

  private excludedNumbers: number[] = [11, 12, 13, 14];

  format(value: string): string {
    if (value) {
      let number = Number.parseInt(value);
      let lastDigit = Math.abs(number) % 10;
      let lastDigits = Math.abs(number) % 100;
      let prefix = "";

      if (this.hasPrefix) {
        prefix = (this.excludedNumbers.includes(lastDigits)
                  ? this.oneDigitPrefix
                  : lastDigit == 1
                    ? this.oneDigitPrefix
                    : this.otherDigitPrefix) + " ";
      }
      let suffix = "";

      if (this.hasSuffix) {
        suffix = " " + (this.excludedNumbers.includes(lastDigits)
                        ? this.otherDigitSuffix
                        : lastDigit == 1
                          ? this.oneDigitSuffix
                          : lastDigit > 1 && lastDigit < 5
                            ? this.fromTwoToFourDigitSuffix
                            : this.otherDigitSuffix);
      }
      return prefix + value + suffix;
    }

    return value;
  }
}
