/*
 * Copyright (C) 2023 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 {AfterViewInit, Component, DestroyRef, inject, Input} from '@angular/core';
import {SCDish, SCISO8601Date, SCPlace} from '@openstapps/core';
import {PlaceMensaService} from './place-mensa-service';
import {Router} from '@angular/router';
import {IonRouterOutlet} from '@ionic/angular/standalone';
import {DataRoutingService} from '../../../../data-routing.service';
import {groupBy} from '@openstapps/collection-utils';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';

/**
 * TODO
 */
@Component({
  providers: [PlaceMensaService],
  selector: 'stapps-place-mensa-detail-content',
  templateUrl: 'place-mensa.html',
  styleUrls: ['place-mensa.scss'],
})
export class PlaceMensaDetailComponent implements AfterViewInit {
  /**
   * Map of dishes for each day
   */
  dishes: Promise<Record<SCISO8601Date, Record<string, SCDish[]>>> | null =
    // eslint-disable-next-line unicorn/no-null
    null;

  /**
   * number of days to display mensa menus for
   */
  @Input() displayRange = 7;

  @Input() item: SCPlace;

  @Input() openAsModal = false;

  /**
   * The currently selected day
   */
  selectedDay: string;

  destroy$ = inject(DestroyRef);

  constructor(
    private readonly mensaService: PlaceMensaService,
    protected router: Router,
    readonly routerOutlet: IonRouterOutlet,
    private readonly dataRoutingService: DataRoutingService,
  ) {}

  ngAfterViewInit() {
    if (!this.openAsModal) {
      this.dataRoutingService
        .itemSelectListener()
        .pipe(takeUntilDestroyed(this.destroy$))
        .subscribe(item => {
          void this.router.navigate(['/data-detail', item.uid], {state: {item}});
        });
    }

    const dishesByDay = this.mensaService.getAllDishes(this.item, this.displayRange);

    dishesByDay.then(result => {
      for (const [key, value] of Object.entries(result)) {
        if (value.length === 0) {
          delete result[key];
        }
      }
      this.selectedDay = Object.keys(result)[0];
    });

    this.dishes = new Promise(async (resolve, reject) => {
      try {
        const dishesBySections: Record<string, Record<string, SCDish[]>> = {};
        for (const [key, value] of Object.entries(await dishesByDay)) {
          dishesBySections[key] = groupBy(value, x => x.menuSection?.name ?? '');
        }
        resolve(dishesBySections);
      } catch {
        // eslint-disable-next-line unicorn/no-null
        reject(null);
      }
    });
  }
}
