/*
 * 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, Input, OnDestroy, OnInit} from '@angular/core';
import {SCThings} from '@openstapps/core';
import {Subscription} from 'rxjs';
import {DataRoutingService} from '../../data/data-routing.service';
import {ActivatedRoute, Router} from '@angular/router';

@Component({
  selector: 'assessments-simple-data-list',
  templateUrl: 'assessments-simple-data-list.html',
  styleUrls: ['assessments-simple-data-list.scss'],
})
export class AssessmentsSimpleDataListComponent implements OnInit, OnDestroy {
  /**
   * All SCThings to display
   */
  _items?: Promise<SCThings[] | undefined>;

  /**
   * Indicates whether or not the list is to display SCThings of a single type
   */
  @Input() singleType = false;

  /**
   * List header
   */
  @Input() listHeader?: string;

  @Input() set items(items: SCThings[] | undefined) {
    this._items = new Promise(resolve => resolve(items));
  }

  subscriptions: Subscription[] = [];

  constructor(
    readonly dataRoutingService: DataRoutingService,
    readonly router: Router,
    readonly activatedRoute: ActivatedRoute,
  ) {}

  ngOnInit() {
    this.subscriptions.push(
      this.dataRoutingService.itemSelectListener().subscribe(thing => {
        void this.router.navigate(['assessments', 'detail', thing.uid], {
          queryParams: {
            token: this.activatedRoute.snapshot.queryParamMap.get('token'),
          },
        });
      }),
    );
  }

  ngOnDestroy() {
    for (const subscription of this.subscriptions) subscription.unsubscribe();
  }
}
