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 { BankInfo } from 'src/modules/sites/bank-info/model/bank-info.model';
import { BankInfoService } from 'src/modules/sites/bank-info/service/bank-info.service';
import { Page } from 'src/modules/common/data/model/page';

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

  constructor(
    private bankInfoService: BankInfoService,
    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<BankInfo> {
    return this.pageSubject.value;
  }

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

  connect(
    collectionViewer: CollectionViewer
  ): Observable<BankInfo[] | readonly BankInfo[]> {
    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.bankInfoService.getBankInfos().pipe(
          map(page => {
            this.page = page;
            return page.content;
          })
        );
      })
    );
  }

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