/*
 * Copyright (C) 2022 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {Component, HostListener, Input, OnInit} from '@angular/core';
import moment from 'moment';
import {Range, ScheduleEvent, ScheduleResponsiveBreakpoint} from '../schema/schema';
import {ScheduleProvider} from '../../../calendar/schedule.provider';
import {SCISO8601Duration, SCUuid} from '@openstapps/core';
import {materialFade} from '../../../../animation/material-motion';
import {groupRangeOverlaps} from './range-overlap';

@Component({
  selector: 'schedule-day',
  templateUrl: 'schedule-day.html',
  styleUrls: ['schedule-day.scss'],
  animations: [materialFade],
})
export class ScheduleDayComponent implements OnInit {
  @Input() day: moment.Moment;

  @Input() hoursRange: Range<number>;

  @Input() uuids: SCUuid[];

  @Input() scale: number;

  @Input() frequencies?: SCISO8601Duration[];

  @Input() layout: ScheduleResponsiveBreakpoint;

  @Input() isLeftmost = false;

  dateSeriesGroups?: ScheduleEvent[][];

  @Input() set dateSeries(value: Record<string, ScheduleEvent>) {
    if (!value) {
      delete this.dateSeriesGroups;
      return;
    }

    this.dateSeriesGroups = groupRangeOverlaps(
      Object.values(value),
      it => it.time.start,
      it => it.time.start + moment.duration(it.time.duration).asHours(),
    ).map(it => it.elements);
  }

  dateFormat = 'dd';

  constructor(protected readonly scheduleProvider: ScheduleProvider) {}

  ngOnInit() {
    this.determineDateFormat();
  }

  @HostListener('window:resize', ['$event'])
  _onResize() {
    this.determineDateFormat();
  }

  private determineDateFormat() {
    this.dateFormat =
      this.layout && window.innerWidth > 1024 && window.innerWidth <= this.layout?.until ? 'dddd' : 'dd';
  }

  // TODO: backend bug results in the wrong date series being returned
  /* async fetchDateSeries(): Promise<ScheduleEvent[]> {
    const dateSeries = await this.scheduleProvider.getDateSeries(
      this.uuids,
      this.frequencies,
      this.momentDay.clone().startOf('day').toISOString(),
      this.momentDay.clone().endOf('day').toISOString(),
    );

    for (const series of dateSeries.dates) {
      console.log(JSON.stringify(series.dates));
    }

    return dateSeries.dates.map(it => ({
      dateSeries: it,
      time: {
        start: moment(it.dates.find(date => date === this.day)).hours(),
        duration: it.duration,
      },
    }));
  } */
}
