import { AfterViewInit, Component, Input, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatSort } from '@angular/material';
import { Pagination, SortField } from '@xdf/commons';
import { DynaDataSource } from '@xdf/gallery';
import { tap } from 'rxjs/operators';
import { UnidentifiedSentenceService } from './services/unidentified-sentences.service';

@Component({
  selector: 'byte-unidentified-sentences-table',
  templateUrl: './unidentified-sentences-table.component.html',
  styleUrls: ['./unidentified-sentences-table.component.scss']
})
export class UnidentifiedSentencesTableComponent implements OnInit, AfterViewInit {

  displayedColumns: string[] = ['identifier', 'count'];
  dataSource: DynaDataSource;
  @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
  @ViewChild(MatSort, { static: false }) sort: MatSort;

  sortColumn = 'count';
  sortDirection = 'desc';
  statusQuickFilter: string;
  pagingSize = 8;

  @Input()
  minDate: Date;

  @Input()
  maxDate: Date;

  pagination: Pagination;

  constructor(protected service: UnidentifiedSentenceService) { }

  ngOnInit() {
    this.dataSource = new DynaDataSource(this.service);

    // Paginación
    this.pagination = new Pagination();
    this.pagination.currentPage = 0;
    this.pagination.itemsPerPage = this.pagingSize;

    this.pagination.filterExpression = 'startDate=' + this.minDate.getTime() + '&&endDate=' + this.maxDate.getTime();

    // Ordenación por defecto
    if (this.sortColumn && this.sortDirection) {
      this.pagination.sortFields = new Array();
      const sortField: SortField = new SortField();
      sortField.direction = this.sortDirection;
      sortField.field = this.sortColumn;
      this.pagination.sortFields.push(sortField);
    }
    this.dataSource.load(this.pagination);
  }


  ngAfterViewInit(): void {
    this.sort.sortChange.subscribe(() => {
      console.log(this.sort);
      if (!this.sort.disabled && this.sort.active) {
        this.pagination.sortFields = new Array();
        const sortField: SortField = new SortField();
        sortField.direction = this.sortDirection = this.sort.direction;
        sortField.field = this.sortColumn = this.sort.active;
        this.pagination.sortFields.push(sortField);
      }

      this.paginator.pageIndex = 0;
      this.dataSource.load(this.pagination);
    });

    this.paginator.page
      .pipe(
        tap(() => {
          this.pagination.currentPage = this.paginator.pageIndex;
          this.pagination.itemsPerPage = this.paginator.pageSize;
          this.dataSource.load(this.pagination);
        })
      )
      .subscribe();
  }

}
