/*
 * Copyright (C) 2021 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 {Router} from '@angular/router';
import {DataRoutingService} from '../data-routing.service';

/**
 * Shows the list of items
 */
@Component({
  selector: 'stapps-simple-data-list',
  templateUrl: 'simple-data-list.html',
  styleUrls: ['simple-data-list.scss'],
})
export class SimpleDataListComponent implements OnInit, OnDestroy {
  /**
   * All SCThings to display
   */
  @Input() items?: SCThings[];

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

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

  /**
   * Items that display the skeleton list
   */
  skeletonItems = 6;

  /**
   * Array of all subscriptions to Observables
   */
  subscriptions: Subscription[] = [];

  constructor(
    protected router: Router,
    private readonly dataRoutingService: DataRoutingService,
  ) {}

  ngOnInit(): void {
    this.subscriptions.push(
      this.dataRoutingService.itemSelectListener().subscribe(item => {
        void this.router.navigate(['data-detail', item.uid]);
      }),
    );
  }

  /**
   * Remove subscriptions when the component is removed
   */
  ngOnDestroy() {
    for (const sub of this.subscriptions) {
      sub.unsubscribe();
    }
  }
}
