import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {PeopleModel} from '../models/people.model';
import {PeopleService} from '../service/people.service';
import {AuthService} from '../service/auth.service';
import {ClonerService} from '../service/clone.service';
import {PageChangeEvent} from '@progress/kendo-angular-pager';

@Component({
  selector: 'app-list-all-people',
  templateUrl: './list-all-people.component.html',
  styleUrls: ['./list-all-people.component.scss'],
})
export class ListAllPeopleComponent implements OnInit {

  private AllPeople: PeopleModel[] = [];
  public filteredPeople: PeopleModel[] = [];
  public displayedPeople: PeopleModel[] = [];

  public skip = 0;
  public pageSize = 12;
  public total = 0;

  constructor(private ps: PeopleService, private auth: AuthService) { }

  ngOnInit(): void {
    this.ps.getPeopleList('').subscribe(
      resp => {
        this.AllPeople = resp.List;
        this.onFilterPeople('');

      }
    );
  }

  public onFilterPeople(hint: string): void {
    if ( hint === undefined || hint.length === 0 ) {
      this.filteredPeople = this.AllPeople.slice(0);
    }else {
      this.filteredPeople = this.AllPeople.filter(
        v => v.Display.toLowerCase().includes(hint.toLowerCase())
      );
    }
    this.skip = 0 ;
    this.total = this.filteredPeople.length;
    this.loadDisplayedPeople();
  }

  public onPeopleSelected(people: PeopleModel): void {
    if ( people !== undefined ) {
      this.filteredPeople = [];
      this.filteredPeople.push(people);
    }else{
      this.filteredPeople = this.AllPeople.slice(0);
    }
    this.loadDisplayedPeople();
  }


  public getContactImageUrl(contactId: string): string {
    return this.auth.getUrl('avatar/' + contactId);
  }

  public onPageChange(e: PageChangeEvent): void {
    this.skip = e.skip;
    this.pageSize = e.take;
    this.loadDisplayedPeople();
  }

  private loadDisplayedPeople(): void {
    this.displayedPeople = this.filteredPeople.slice(this.skip, this.skip + this.pageSize);
    this.total = this.filteredPeople.length;
  }
}
