/*
 * Copyright (C) 2023 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, ContentChild, DestroyRef, inject, Input, OnInit, TemplateRef} from '@angular/core';
import {SCThings} from '@openstapps/core';
import {Router} from '@angular/router';
import {DataRoutingService} from '../data-routing.service';
import {DataListContext} from './data-list.component';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';

/**
 * 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 {
  @Input() items?: Promise<SCThings[] | undefined>;

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

  @Input() autoRouting = true;

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

  @Input() emptyListMessage?: string;

  @ContentChild(TemplateRef) listItemTemplateRef: TemplateRef<DataListContext<SCThings>>;

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

  destroy$ = inject(DestroyRef);

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

  ngOnInit(): void {
    if (!this.autoRouting) return;
    this.dataRoutingService
      .itemSelectListener()
      .pipe(takeUntilDestroyed(this.destroy$))
      .subscribe(item => {
        void this.router.navigate(['/data-detail', item.uid], {state: {item}});
      });
  }
}
