/*
 * 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, OnDestroy, OnInit} from '@angular/core';
import {SCBuilding, SCFloor, SCPointOfInterest, SCRoom, SCThings} 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 {Subscription} from 'rxjs';

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

  @Input() openAsModal = false;

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

  itemRouting: Subscription;

  /**
   * TODO
   *
   * @param item TODO
   */
  hasCategories(item: SCThings): item is SCThings & {categories: string[]} {
    return typeof (item as {categories: string[]}).categories !== 'undefined';
  }

  /**
   * Helper function as 'typeof' is not accessible in HTML
   *
   * @param item TODO
   */
  isMensaThing(item: SCThings): boolean {
    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) {
    this.itemRouting = dataRoutingService.itemSelectListener().subscribe(item => {
      void router.navigate(['/data-detail', item.uid]);
    });
  }

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

  ngOnDestroy() {
    this.itemRouting.unsubscribe();
  }
}
