import { DatePickerTranslations, Internationalization } from './../../constants/constants';
import { bindable, customElement } from "aurelia-framework";
import { IDateConfig, isDisabled } from "./calendar-utils";
import { DateUtils } from '../../utils/date-utils';

@customElement("days-page")
export class DaysPage {
  @bindable()
  public date: Date;

  @bindable()
  public config: IDateConfig;

  @bindable()
  public displayWeek: boolean = false;

  @bindable()
  private translations: DatePickerTranslations = Internationalization.datePickerTranslationsEN;

  protected pageStart: Date;
  protected isAttached: boolean = false;
  protected weekStartsOn: 0 | 1 | 2 | 3 | 4 | 5 | 6 = 1;
  protected weekNumbers: Array<number>;

  constructor(private dateUtils: DateUtils) {

  }

  protected attached(): void {
    this.isAttached = true;
    this.weekNumbers = new Array<number>();
    for (let index = 0; index < 7; index++) {
      let weekNumber = index + this.weekStartsOn;
      if (weekNumber >= 7) weekNumber -= 7;
      this.weekNumbers.push(weekNumber);
    }
  }

  protected dateChanged(newDate) {
    this.date = newDate || new Date();
    this.pageStart = this.dateUtils.getStartOfWeek(newDate || this.dateUtils.getStartOfMonth(this.date));
  }

  protected weekNumber(week: number): KeyValue {
    let date = this.dateUtils.addWeeks(this.pageStart, week);
    return { date, label: this.dateUtils.getNumOfWeek(date)?.toLocaleString('fr-BE', { minimumIntegerDigits: 2, useGrouping: false }) };
  }

  protected getDate(week: number, day: number): KeyValue {
    const date = this.dateUtils.addDays(this.dateUtils.addWeeks(this.pageStart, week), day);

    const classes = [];
    if (!this.dateUtils.isSameMonth(this.date, date)) {
      classes.push("date-other");
    }
    if (this.dateUtils.isSameDay(new Date(), date)) {
      classes.push("date-today");
    }
    if (this.config) {
      if (isArray(this.config.date)) {
        if (
          this.dateUtils.isAfter(this.dateUtils.getStartOfDay(date), this.config.date[0]) &&
          this.dateUtils.isBefore(this.dateUtils.getStartOfDay(date), this.config.date[1])
        ) {
          classes.push("select-hilight");
        }
        if (this.dateUtils.isSameDay(this.config.date[0], date)) {
          classes.push("select-start");
        }

        if (this.dateUtils.isSameDay(this.config.date[1], date)) {
          classes.push("select-end");
        }
      }
      if (isDate(this.config.date) && this.dateUtils.isSameDay(this.config.date, date)) {
        classes.push("selected");
      }
      if (isDisabled(this.config, date, this.dateUtils)) {
        classes.push("disabled");
      }
    }
    if (date.getDay() == 0 || date.getDay() == 6) {
      classes.push("date-week-end");
    }
    return { date: date, label: date.getDate(), classes: classes.join(" ") };
  }
}
