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

@AnalyticalScope(Text)
export class UnionAgeAndBirthDateTextScript extends Behavior {

  @ObjectRef()
  @NotNull()
  public inputBirthDate: ControlWithValue;

  private text: Text;
  private readonly onChangeFunction = () => {
    if (this.text) {
      const birthDate = this.parseToIsoFormat(this.inputBirthDate.getTextValue());
      this.text.setValue(this.format(new Date(birthDate)));
    }
  }

  initialize() {
    super.initialize();
    this.text = this.getScript(Text);
  }

  bindEvents() {
    super.bindEvents();
    this.inputBirthDate.addChangeListener(this.onChangeFunction)
  }

  unbindEvents() {
    super.unbindEvents();
    this.inputBirthDate.removeChangeListener(this.onChangeFunction);
  }

  private format(birthdate: Date): string {
    const age = this.calculateAge(birthdate)
    const ageString = this.getTextAge(age);
    const strBirthDate = birthdate.getFullYear();
    return `${age} ${ageString}, ${strBirthDate}`;
  }

  private getTextAge(age: number) {
    if (age % 10 === 1 && age % 100 !== 11) {
      return 'год';
    } else if (age % 10 >= 2 && age % 10 <= 4 &&
               (age % 100 < 10 || age % 100 >= 20)) {
      return 'года';
    } else {
      return 'лет';
    }
  }

  private calculateAge(birthDate: Date) {
    const currentDate = new Date();
    let age = currentDate.getFullYear() - birthDate.getFullYear();

    const difMonthValue = currentDate.getMonth() - birthDate.getMonth();
    if (difMonthValue < 0 || (difMonthValue === 0 && currentDate.getDate() < birthDate.getDate())) {
      age--;
    }

    return age;
  }

  private parseToIsoFormat(date: string): string {
    let strings = date.split('.');
    return `${strings[2]}-${strings[1]}-${strings[0]}`;
  }
}