import {AnalyticalScope, Behavior, NotNull, ObjectRef, Text} from "@webbpm/base-package";

@AnalyticalScope(Text)
export class DigitDependentValue extends Behavior {

  @ObjectRef()
  @NotNull()
  public parent: Text;

  @NotNull()
  public oneDigitValue: string;
  @NotNull()
  public fromTwoToFourDigitValue: string;
  @NotNull()
  public otherDigitValue: string;

  private text: Text;
  private parentValueChangeListener: Function;
  private excludedNumbers: number[] = [11, 12, 13, 14];

  initialize() {
    super.initialize();
    this.text = this.getScript(Text);
    this.parentValueChangeListener = () => {
      let value = this.parent.getValue();

      if (value) {
        this.text.setValue(this.getValueDependOn(value));
        this.text.setTooltip(this.text.getValue());
      }
    };
  }

  private getValueDependOn(parentValue: string) {
    let number = Number.parseInt(parentValue);
    let lastDigit = Math.abs(number) % 10;
    let lastDigits = Math.abs(number) % 100;
    return this.excludedNumbers.includes(lastDigits)
            ? this.otherDigitValue
            : lastDigit == 1
              ? this.oneDigitValue
              : lastDigit > 1 && lastDigit < 5
                ? this.fromTwoToFourDigitValue
                : this.otherDigitValue;
  }

  bindEvents() {
    super.bindEvents();
    this.parent.addChangeListener(this.parentValueChangeListener);
  }

  unbindEvents() {
    super.unbindEvents();
    this.parent.removeChangeListener(this.parentValueChangeListener);
  }
}