/*
 * 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 {CdkVirtualScrollViewport} from '@angular/cdk/scrolling';
import {
  Component,
  EventEmitter,
  HostListener,
  Input,
  OnChanges,
  OnDestroy,
  OnInit,
  Output,
  SimpleChanges,
  ViewChild,
} from '@angular/core';
import {SCThings} from '@openstapps/core';
import {BehaviorSubject, Observable, Subscription} from 'rxjs';

/**
 * Shows the list of items
 */
@Component({
  selector: 'stapps-data-list',
  templateUrl: 'data-list.html',
  styleUrls: ['data-list.scss'],
})
export class DataListComponent implements OnChanges, OnInit, OnDestroy {
  /**
   * Amount of list items left to show (in percent) that should trigger a data reload
   */
  private readonly reloadThreshold = 0.2;

  /**
   * All SCThings to display
   */
  @Input() items?: 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;

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

  @ViewChild(CdkVirtualScrollViewport) viewPort: CdkVirtualScrollViewport;

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

  /**
   * 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) && typeof changes.items !== 'undefined') {
      this.itemStream.next(this.items);
    }
  }

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

  ngOnInit(): void {
    this.calcSkeletonItems();
    if (typeof this.resetToTop !== 'undefined') {
      this.subscriptions.push(
        this.resetToTop.subscribe(() => {
          this.viewPort.scrollToIndex(0);
        }),
      );
    }
  }

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

  /**
   * Function to call whenever scroll view visible range changed
   */
  scrolled(index: number) {
    if (
      // first condition prevents "load more" to be executed even before scrolling
      index > 0 &&
      (this.items?.length ?? 0) - this.viewPort.getRenderedRange().end <=
        (this.items?.length ?? 0) * this.reloadThreshold
    ) {
      this.notifyLoadMore();
    }
  }
}
