import { DataSource } from '@angular/cdk/table';

import { BehaviorSubject, Observable, merge } from 'rxjs';
import { switchMap, map } from 'rxjs/operators';

import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { CollectionViewer } from '@angular/cdk/collections';

import { League } from 'src/modules/game/model/league.model';
import { LeagueService } from 'src/modules/game/service/league.service';
import { Page } from 'src/modules/common/data/model/page';

export class LeagueDataSource extends DataSource<League> {
  private filterSubject = new BehaviorSubject('');
  private pageSubject = new BehaviorSubject<Page<League>>({});

  constructor(
    private leagueService: LeagueService,
    private paginator: MatPaginator,
    private sort: MatSort
  ) {
    super();
  }

  // Filter
  get filter(): string {
    return this.filterSubject.value;
  }

  set filter(filter: string) {
    this.filterSubject.next(filter);
  }

  get page(): Page<League> {
    return this.pageSubject.value;
  }

  set page(value: Page<League>) {
    this.pageSubject.next(value);
  }

  connect(
    collectionViewer: CollectionViewer
  ): Observable<League[] | readonly League[]> {
    const displayDataChanges = [
      this.paginator.page,
      this.sort.sortChange,
      this.filterSubject
    ];

    return merge(...displayDataChanges).pipe(
      switchMap(() => {
        const filter = this.filter;
        const sortActive = this.sort.active;
        const sortDirection = this.sort.direction;
        const pageIndex = this.paginator.pageIndex;
        const pageSize = this.paginator.pageSize;

        return this.leagueService.getAllLeague().pipe(
          map(page => {
            this.page = page;
            return page.content;
          })
        );
      })
    );
  }

  disconnect(collectionViewer: CollectionViewer): void {
    this.filterSubject.complete();
  }
}
