/*
 * 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, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {TranslateService} from '@ngx-translate/core';
import {SCUuid} from '@openstapps/core';
import {FavoritesService} from '../../favorites/favorites.service';
import {DataProvider} from '../../data/data.provider';
import {DataDetailComponent} from '../../data/detail/data-detail.component';
import {DaiaDataProvider} from '../daia-data.provider';
import {DaiaHolding} from '../protocol/response';
import {ModalController} from '@ionic/angular';
import {groupByStable} from '../../../_helpers/collections/group-by';

/**
 * A Component to display an SCThing detailed
 */
@Component({
  selector: 'stapps-daia-availability',
  styleUrls: ['daia-availability.scss'],
  templateUrl: 'daia-availability.html',
})
export class DaiaAvailabilityComponent extends DataDetailComponent implements OnInit {
  holdings?: DaiaHolding[];

  holdingsByDepartments?: Map<DaiaHolding['department']['id'], DaiaHolding[]>;

  /**
   *
   * @param route the route the page was accessed from
   * @param dataProvider the data provider
   * @param favoritesService the favorites provider
   * @param modalController the modal controller
   * @param translateService he translate provider
   * @param daiaDataProvider DaiaDataProvider
   */
  constructor(
    route: ActivatedRoute,
    dataProvider: DataProvider,
    favoritesService: FavoritesService,
    modalController: ModalController,
    translateService: TranslateService,
    private daiaDataProvider: DaiaDataProvider,
  ) {
    super(route, dataProvider, favoritesService, modalController, translateService);
  }

  /**
   * Initialize
   */
  async ngOnInit() {
    const uid = this.route.snapshot.paramMap.get('uid');
    if (uid) {
      await this.getAvailability(uid);
    }
  }

  /**
   * Provides data item with given UID
   *
   * @param uid Unique identifier of a thing
   */
  async getAvailability(uid: SCUuid) {
    this.daiaDataProvider.getAvailability(uid).then(holdings => {
      if (holdings !== undefined) {
        this.holdings = holdings;
        this.holdingsByDepartments = groupByStable(holdings, holding => holding.department.id);
      }
    });
  }
}
