import {Component, EventEmitter, forwardRef, Input, OnInit, Output, ViewChild} from '@angular/core';
import {AuthService} from '../service/auth.service';
import {ControlValueAccessor, FormControl, FormGroup, NG_VALUE_ACCESSOR} from '@angular/forms';
import {MultiColumnComboBoxComponent} from '@progress/kendo-angular-dropdowns';
import {PeopleService} from '../service/people.service';
import {UserExModel} from '../models/userExModel';

@Component({
  selector: 'app-people-select',
  templateUrl: './people-select.component.html',
  styleUrls: ['./people-select.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => PeopleSelectComponent),
      multi: true
    }
  ]
})
export class PeopleSelectComponent implements OnInit, ControlValueAccessor {

  @Input() disabled = false;
  @Input() placeholder: string;
  @Input() searchWithin: UserExModel[] = [];
  @Input() formControl: FormControl = new FormControl(); // this is a dummy place holder
  @Output() valueChange: EventEmitter<UserExModel> = new EventEmitter<UserExModel>();
  @ViewChild('list', {static: true}) public text: MultiColumnComboBoxComponent;

  public searchResult: UserExModel[] = [];
  public value = ''; // selecting the default and only empty contact element // TODO: remove ngModel
  public total = 0;


  // Function to call when the rating changes.
  private onChange = ( nameOrId: UserExModel) => {};
  // Function to call when the input is touched (when a star is clicked).
  private onTouched = () => {};

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

  ngOnInit(): void {
    this.loadFilteredPeopleList(''); // load every one
  }

  private loadFilteredPeopleList( filter: string): void {
    this.text.loading = true;
    this.ps.getUserExList(filter).subscribe(
      resp => {
        this.text.loading = false;
        this.searchWithin = resp.List;
        this.total = resp.Count;
        this.searchResult = this.searchWithin;
      },
      error => { this.text.loading = false; },
      () => { this.text.loading = false; }
    );
  }

  filterChange(filter: string): void {
    this.searchResult = [];
    this.searchWithin.forEach( v => {
      if ( filter === '' ){
        this.searchResult.push(v);
      } else if ( v.Id === filter) {
        this.searchResult.push (v);
      } else if ( v.Display.includes( filter ) ){
        this.searchResult.push(v);
      }
    });
  }

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

  // ComboBox emit event on value change
  public onSelectionChange(str: string): void {
    const p = this.searchWithin.find( v => v.Id === str);
    if ( p ){
      this.onChange(p);
    }
  }

  writeValue(inV: UserExModel): void {
    console.log( ' value in', inV);
    if (inV){
      this.value = inV.Id;
    }else{
      this.value = null;
    }
  }

  // Allows Angular to register a function to call when the model (rating) changes.
  // Save the function as a property to call later here.
  registerOnChange(fn: (nameOrId: UserExModel) => void): void {
    this.onChange = fn;
  }
  // Allows Angular to register a function to call when the input has been touched.
  // Save the function as a property to call later here.
  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }
  // Allows Angular to disable the input.
  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }

  public showDropDown(): void{
    this.text.toggle(true);
  }
}
