import {Component, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {CellCloseEvent, DataStateChangeEvent, GridComponent, GridDataResult} from '@progress/kendo-angular-grid';
import {CompositeFilterDescriptor, SortDescriptor, toODataString} from '@progress/kendo-data-query';
import {LoanSummaryService} from '../service/loan_summary.service';
import {AuthService} from '../service/auth.service';
import {Observable} from 'rxjs';
import {Router} from '@angular/router';

@Component({
  selector: 'app-list-all-loans',
  templateUrl: './list-all-loans.component.html',
  styleUrls: ['./list-all-loans.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class ListAllLoansComponent implements OnInit {
  public view: LoanSummaryService;
  public sort: Array<SortDescriptor> = [{dir: 'desc', field: 'Settlement'}];
  public filter: CompositeFilterDescriptor;
  public pageSize = 10;
  public skip = 0;



  @ViewChild(GridComponent, { static: true }) public grid: GridComponent;


  constructor(private service: LoanSummaryService, private auth: AuthService, private router: Router) { }

  public ngOnInit(): void {
    // Bind directly to the service as it is a Subject
    this.view = this.service;

    // Fetch the data with the initial state
    this.loadData();
  }

  public dataStateChange({ skip, take, sort, filter }: DataStateChangeEvent): void {
    // Save the current state of the Grid component
    this.skip = skip;
    this.pageSize = take;
    this.sort = sort;
    this.filter = filter;

    // Reload the data with the new state
    this.loadData();

    // Expand the first row initially
    // this.grid.expandRow(0);
  }

  public filterChange(filter: CompositeFilterDescriptor): void {
    this.filter = filter;
    console.log(filter);
  }
  private loadData(): void {
    this.service.query({ skip: this.skip, take: this.pageSize, sort: this.sort, filter: this.filter});
  }

  private photoURL(peopleId: any): string {
    const url = this.auth.getUrl('avatar/') + peopleId;
    return 'url("' + url + '")';
  }

  public allowEdit(): boolean {
    return this.auth.allowEditLoan();
  }

  public allData = (): Observable<GridDataResult> => {
    return this.service.queryAll({skip: 0, take: 999999, sort: this.sort, filter: this.filter});
  }

  public onCellClick(event: CellCloseEvent): void {
    this.router.navigate(['/edit-loan/' + event.dataItem.Id]);
  }


}
