import { Component, OnInit } from '@angular/core';
import {LoanSummaryService} from '../service/loan_summary.service';
import {SessionService} from '../service/session.service';
import {AppConfig} from '../app.config';
import {CompositeFilterDescriptor, SortDescriptor} from '@progress/kendo-data-query';
import {PageChangeEvent} from '@progress/kendo-angular-listview';

@Component({
  selector: 'app-loan-row-list',
  templateUrl: './loan-row-list.component.html',
  styleUrls: ['./loan-row-list.component.scss']
})
export class LoanRowListComponent implements OnInit {
  public allLoans: LoanSummaryService;
  public skip: number = 0
  public take: number = 10;
  constructor(private lss: LoanSummaryService, private ss: SessionService, private config: AppConfig) { }

  ngOnInit(): void {
    this.allLoans = this.lss;
    this.LoadLoansForCurrentUser()
  }

  public LoadLoansForCurrentUser() {
    let people = this.ss.loggedIn.User;
    const sort: Array <SortDescriptor> = [{dir:  'desc', field:  'Settlement'}];
    if ( this.ss.loggedIn.role.toLowerCase() == 'admin' || this.ss.loggedIn.role.toLowerCase() == 'manager' ){
      const filter: CompositeFilterDescriptor = {logic: 'and',  filters: []  };
      this.lss.query({ skip: this.skip, take: this.take, sort, filter});
    }else{ // load broker's loans
      const filter: CompositeFilterDescriptor = {logic: 'or',  filters: []  };
      filter.filters.push({field:'client_ids', operator: 'contains', value: people.Id, ignoreCase: true})
      filter.filters.push({field:'broker_ids', operator: 'contains', value: people.Id, ignoreCase: true})
      filter.filters.push({field:'other_rewarder_ids', operator: 'contains', value: people.Id, ignoreCase: true})
      this.lss.query({ skip: this.skip, take: this.take, sort, filter});
    }
  }

  public handleFilterChange(query: string): void {
    const normalizedQuery = query.toLowerCase();
    const filterExpession = (item) =>
      item.productName.toLowerCase().indexOf(normalizedQuery) !== -1 ||
      item.categoryName.toLowerCase().indexOf(normalizedQuery) !== -1;

    console.log(normalizedQuery, filterExpession);
  }

  public handlePageChange( event: PageChangeEvent) {
    this.skip = event.skip;
    this.take = event.take;
    this.LoadLoansForCurrentUser();
  }
}
