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

export class HandlersDataSource extends DataSource<Handler> {

  private handlerSubject = new BehaviorSubject<Handler[]>([]);
  private loadingSubject = new BehaviorSubject<boolean>(false);

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

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

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

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

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


  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);
    };
  };
}