import { DataSource } from "@angular/cdk/collections";
import { Package } from "../api/models/package"
import { BehaviorSubject, Observable, retry, map, catchError, of, finalize } from "rxjs";
import { PkgdashService } from "../api/services";

export class PackagesDataSource extends DataSource<Package> {

  private packageSubject = new BehaviorSubject<Package[]>([]);
  private loadingSubject = new BehaviorSubject<boolean>(false);

  public loading$ = this.loadingSubject.asObservable();

  constructor(
    private pkgdashService: PkgdashService
  ) {
    super();
  }

  connect(): Observable<Package[]> {
    return this.packageSubject.asObservable();
  }

  disconnect(): void {
    this.packageSubject.complete();
    this.loadingSubject.complete();
  }

  list(filter = '', sortField = 'name', sortOrder = 'asc', page = 0, limit = 20) {
    this.loadingSubject.next(true);
    this.pkgdashService.packageList().pipe(
      retry(2),
      map(rsp => rsp.packages || []),
      catchError(this.handleError('list', [])),
      finalize(() => this.loadingSubject.next(false))
    ).subscribe(packages => this.packageSubject.next(packages));
  }

  lookup(id: number, filter: string,
    sortDirection: string, pageIndex: number, pageSize: number) {
  }

  private handleError<T>(operation = '', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  };
}