/*
 * 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,
  EventEmitter,
  HostListener,
  inject,
  Input,
  OnChanges,
  OnInit,
  Output,
  SimpleChanges,
  TemplateRef,
  ViewChild,
} from '@angular/core';
import {SCThings} from '@openstapps/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {IonInfiniteScroll} from '@ionic/angular/standalone';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';

export interface DataListContext<T> {
  $implicit: T;
}

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

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

  /**
   * Stream of SCThings for virtual scroll to consume
   */
  itemStream = new BehaviorSubject<SCThings[]>([]);

  /**
   * Output binding to trigger pagination fetch
   */
  // eslint-disable-next-line @angular-eslint/no-output-rename
  @Output('loadmore') loadMore = new EventEmitter<void>();

  /**
   * Emits when scroll view should reset to top
   */
  @Input() resetToTop?: Observable<void>;

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

  /**
   * Items that display the skeleton list
   */
  skeletonItems: number;

  @ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll;

  /**
   * Signalizes that the data is being loaded
   */
  @Input() loading = true;

  destroy$ = inject(DestroyRef);

  /**
   * Calculate how many items would fill the screen
   */
  @HostListener('window:resize', ['$event'])
  calcSkeletonItems() {
    const itemHeight = 40;
    this.skeletonItems = Math.ceil(window.innerHeight / itemHeight);
  }

  /**
   * Uniquely identifies item at a certain list index
   */
  // eslint-disable-next-line class-methods-use-this
  identifyItem(_index: number, item: SCThings) {
    return item.uid;
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (Array.isArray(this.items) && changes.items !== undefined) {
      this.itemStream.next(this.items);
      this.infiniteScroll.complete();
    }
  }

  ngOnInit(): void {
    this.calcSkeletonItems();
    if (this.resetToTop !== undefined) {
      this.resetToTop.pipe(takeUntilDestroyed(this.destroy$)).subscribe(() => {
        // this.viewPort.scrollToIndex(0);
      });
    }
  }

  /**
   * Component proxy for dataSource.finishedLoadMore
   */
  notifyLoadMore() {
    this.loadMore.emit();
  }
}
