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

@Component({
  selector: 'assessments-simple-data-list',
  templateUrl: 'assessments-simple-data-list.html',
  styleUrls: ['assessments-simple-data-list.scss'],
})
export class AssessmentsSimpleDataListComponent implements OnInit {
  /**
   * 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));
  }

  destroy$ = inject(DestroyRef);

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

  ngOnInit() {
    this.dataRoutingService
      .itemSelectListener()
      .pipe(takeUntilDestroyed(this.destroy$))
      .subscribe(thing => {
        void this.router.navigate(['assessments', 'detail', thing.uid], {
          queryParams: {
            token: this.activatedRoute.snapshot.queryParamMap.get('token'),
          },
          state: {item: thing},
        });
      });
  }
}
