import { Component, ChangeDetectionStrategy, Host } from '@angular/core';
import { DateAdapter } from '@ui/common';
import { combineLatest } from 'rxjs';
import { map } from 'rxjs/operators';
import { UiCalendarComponent } from '../ui-calendar.component';

@Component({
  selector: 'ui-calendar-body',
  templateUrl: 'calendar-body.component.html',
  styleUrls: ['calendar-body.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UiCalendarBodyComponent {
  weeks$ = combineLatest([this.calendar.mode$, this.calendar.displayed$, this.calendar.indicators$]).pipe(
    map(([mode, displayed]) => {
      const weeks: { week: number; dates: Date[] }[] = [];
      if (mode === 'week') {
        const week = this.dateAdapter.getCalendarWeek(displayed);
        weeks.push({
          week,
          dates: this.dateAdapter.getDatesForCalendarWeek(this.dateAdapter.getYear(displayed), week),
        });
      } else if (mode === 'month') {
        return this.dateAdapter.getDatesAndCalendarWeeksForMonth(displayed);
      }
      return weeks;
    })
  );

  indicators$ = this.calendar.indicators$;

  constructor(@Host() public calendar: UiCalendarComponent, private dateAdapter: DateAdapter) {}

  selectDate(date: Date) {
    this.calendar.setSelected(date);
  }
}
