/*
 * 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 {Component, Input, OnInit} from '@angular/core';
import {SCBuilding, SCFloor, SCPointOfInterest, SCRoom, SCThings, SCPlace} from '@openstapps/core';
import {DataProvider} from '../../data.provider';
import {hasValidLocation, isSCFloor} from './place-types';
import {DataRoutingService} from '../../data-routing.service';
import {Router} from '@angular/router';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';

@Component({
  providers: [DataProvider],
  styleUrls: ['place-detail-content.scss'],
  selector: 'stapps-place-detail-content',
  templateUrl: 'place-detail-content.html',
})
export class PlaceDetailContentComponent implements OnInit {
  @Input() item: SCBuilding | SCRoom | SCPointOfInterest | SCFloor;

  @Input() openAsModal = false;

  /**
   * Does it have a valid location or not (for showing in a map widget)
   */
  hasValidLocation = false;

  hasCategories(item: object): item is SCThings & {categories: string[]} {
    return (item as {categories: string[]}).categories !== undefined;
  }

  /**
   * Helper function as 'typeof' is not accessible in HTML
   * @param item TODO
   */
  isMensaThing(item: SCThings | SCPlace): item is SCPlace {
    return (
      this.hasCategories(item) &&
      ((item.categories as string[]).includes('canteen') ||
        (item.categories as string[]).includes('cafe') ||
        (item.categories as string[]).includes('student canteen') ||
        (item.categories as string[]).includes('restaurant'))
    );
  }

  constructor(dataRoutingService: DataRoutingService, router: Router) {
    dataRoutingService
      .itemSelectListener()
      .pipe(takeUntilDestroyed())
      .subscribe(item => {
        void router.navigate(['/data-detail', item.uid], {state: {item}});
      });
  }

  ngOnInit() {
    this.hasValidLocation = !isSCFloor(this.item) && hasValidLocation(this.item);
  }
}
