/*
 * 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, inject, OnInit} from '@angular/core';
import {SCUuid} from '@openstapps/core';
import {DataDetailComponent} from '../../data/detail/data-detail.component';
import {DaiaDataProvider} from '../daia-data.provider';
import {DaiaHolding} from '../protocol/response';
import {groupByStable} from '@openstapps/collection-utils';

/**
 * 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[]>;

  private daiaDataProvider = inject(DaiaDataProvider);

  /**
   * @override
   */
  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);
      }
    });
  }
}
