import {
  ChangeDetectionStrategy,
  Component,
  Input,
  OnInit,
} from '@angular/core';
import { isWithinInterval } from 'date-fns';
import { combineLatest, interval, map, Observable, startWith } from 'rxjs';
import {
  GetTourAmountPerTimeKpiGQL,
  GetTourAmountPerTimeKpiQuery,
} from '../../../../core/data-access/graphql/generated/generated';

@Component({
    selector: 'dks-tours-per-time-kpi',
    templateUrl: './tours-per-time-kpi.component.html',
    styleUrls: ['./tours-per-time-kpi.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    standalone: false
})
export class ToursPerTimeKPIComponent implements OnInit {
  @Input() ordinanceType!: string;

  toursPerTimeKPI$!: Observable<
    GetTourAmountPerTimeKpiQuery['toursPerTimeKPI']
  >;
  currentTimeSlot$!: Observable<number>;

  constructor(
    private readonly getToursPerTimeKPIGql: GetTourAmountPerTimeKpiGQL
  ) {}

  ngOnInit(): void {
    this.toursPerTimeKPI$ = this.getToursPerTimeKPIGql
      .watch({ ordinanceType: this.ordinanceType }, { pollInterval: 60000 })
      .valueChanges.pipe(map((result) => result.data.toursPerTimeKPI));
    this.currentTimeSlot$ = combineLatest([
      interval(60000).pipe(startWith(0)),
      this.toursPerTimeKPI$,
    ]).pipe(
      map(([, kpis]) =>
        kpis.findIndex((kpi) =>
          this.isInInterval({
            start: kpi.interval.start,
            end: kpi.interval.end,
          })
        )
      )
    );
  }

  isInInterval(interval: { start: string; end: string }): boolean {
    return isWithinInterval(new Date(), {
      start: new Date(interval.start),
      end: new Date(interval.end),
    });
  }
}
