import { Component, OnInit, ViewChild, AfterViewInit, ElementRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { tap, merge, debounceTime, distinctUntilChanged, fromEvent } from 'rxjs';
//import { Location } from '@angular/common';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort, Sort, SortDirection } from '@angular/material/sort';
import { AppConstants } from 'src/app/app.constants';
import { MessageService } from 'src/app/services/message/message.service';
import { ErrorRsp, Handler, Package } from 'src/app/api/models';
import { PkgdashService } from 'src/app/api/services';
import { HandlersDataSource } from 'src/app/datasources/handlers';

@Component({
  selector: 'app-package',
  templateUrl: './package.component.html',
  styleUrls: ['./package.component.scss'],
  providers: [PkgdashService],
})

export class PackageComponent implements OnInit, AfterViewInit {
  @ViewChild(MatPaginator) paginator!: MatPaginator;
  @ViewChild(MatSort) sort!: MatSort;
  @ViewChild('input') input!: ElementRef;

  package!: Package;

  public itemsCount = 10;
  sortField = 'name';
  sortOrder: SortDirection = 'asc';

  displayedColumns: string[] = ['name', 'coverage'];

  dataSource: HandlersDataSource;
  selectedRowIndex: any;

  constructor(
    private route: ActivatedRoute,
    //private location: Location,
    private pkgdashService: PkgdashService,
    private messageService: MessageService,
  ) {
    this.dataSource = new HandlersDataSource(this.pkgdashService);
  }

  highlight(row: Handler) {
    this.selectedRowIndex = row.id;
  }

  ngAfterViewInit() {

    fromEvent(this.input.nativeElement, 'keyup')
      .pipe(
        debounceTime(AppConstants.SEARCH_DEBOUNCE),
        distinctUntilChanged(),
        tap(() => {
          this.paginator.pageIndex = 0;
          this.loadHandlers();
        })
      )
      .subscribe();

    this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);

    merge(this.sort.sortChange, this.paginator.page)
      .pipe(
        tap(() => this.loadHandlers())
      )
      .subscribe();
  }

  public sortHandlers(event: Sort): void {
    this.loadHandlers()
  }

  private loadHandlers(): void {
    this.dataSource.list(
      this.package.id!,
      '',
      this.sort.active,
      this.sort.direction,
      this.paginator.pageIndex,
      this.paginator.pageSize);
  }


  ngOnInit(): void {
    this.package = this.route.snapshot.data['package'];
    this.dataSource.list(this.package.id!, '', this.sortField, this.sortOrder, 0, this.itemsCount);
    this.selectedRowIndex = 1;
  }

}
