import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { Datepicker } from '@isa-ui/datepicker/datepicker';
import { DateAdapter } from '@isa-ui/core/date';
import { map } from 'rxjs/operators';
@Component({
  selector: 'app-ui-datepicker-body',
  templateUrl: 'body.component.html',
  styleUrls: ['body.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UiDatepickerBodyComponent<TDate> implements OnInit {
  selected$ = this.datepicker.selected$;
  displayed$ = this.datepicker.displayed$;
  min$ = this.datepicker.min$;
  max$ = this.datepicker.max$;

  dates$ = this.datepicker.displayed$.pipe(map((date) => this.getDateCellsForDate(date)));

  constructor(private datepicker: Datepicker<TDate>, private dateAdapter: DateAdapter<TDate>) {}

  ngOnInit() {}

  getDateCellsForDate(date: TDate): TDate[][] {
    const firstDateOfMonth = this.dateAdapter.getFirstDateOfMonth(date);
    const firstCalendarDate = this.dateAdapter.getFirstDateOfWeek(firstDateOfMonth);
    const lastDateOfMonth = this.dateAdapter.getLastDateOfMonth(date);
    const lastCalendarDate = this.dateAdapter.getLastDateOfWeek(lastDateOfMonth);

    const dates: TDate[][] = [];

    const days = this.dateAdapter.getDifferenceInDays(lastCalendarDate, firstCalendarDate);

    for (let day = 0; day <= days; day++) {
      if (day % 7 === 0) {
        dates.push([]);
      }

      const current = this.dateAdapter.addCalendarDays(firstCalendarDate, day);
      dates[dates.length - 1].push(current);
    }

    return dates;
  }

  selectDate(date: TDate) {
    this.datepicker.setSelected(date);
  }
}
