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

@AnalyticalScope(TextField)
export class BirthDateRageCalculator extends Behavior {

  @ObjectRef()
  @NotNull()
  public startDate: DateTimePicker;

  @ObjectRef()
  @NotNull()
  public endDate: DateTimePicker;

  private ageField: TextField;
  private onUpdateFunction: Function;

  public initialize() {
    super.initialize();
    this.ageField = this.getScript(TextField);
    if (!this.ageField) {
      throw new ScriptLocationError(TextField.name, this);
    }
    this.onUpdateFunction = () => {
      const age = this.ageField.getTextValue();
      this.startDate.setValueAsDate(this.getStartDate(age));
      this.endDate.setValueAsDate(this.getEndDate(age));
    }
  }

  public bindEvents() {
    super.bindEvents();
    this.ageField.addUserChangeValueListener(this.onUpdateFunction);
  }

  public unbindEvents() {
    super.unbindEvents();
    this.ageField.removeUserChangeValueListener(this.onUpdateFunction);
  }

  protected getStartDate(age: string) : Date {
    if (age !== null && age !== "") {
      const date = new Date(
          new Date().getFullYear() - Number(age) - 1,
          new Date().getMonth(),
          new Date().getDay()
      );
      date.setDate(date.getDate() + 1);
      return date;
    }
    return null;
  }

  protected getEndDate(age: string) : Date {
    if (age !== null && age !== "") {
      return new Date(
          new Date().getFullYear() - Number(age),
          new Date().getMonth(),
          new Date().getDay(),
      );
    }
    return null;
  }
}