import {Component, OnInit, ViewChild} from '@angular/core';
import {BrokerModel} from '../models/broker.model';
import {PeopleService} from '../service/people.service';
import {AuthService} from '../service/auth.service';
import {ClonerService} from '../service/clone.service';
import {BrokerRewardComponent} from '../broker-reward/broker-reward.component';
import {ComboBoxComponent} from '@progress/kendo-angular-dropdowns';

@Component({
  selector: 'app-admin-reward-by-broker',
  templateUrl: './admin-reward-by-broker.component.html',
  styleUrls: ['./admin-reward-by-broker.component.scss']
})
export class AdminRewardByBrokerComponent implements OnInit {
  public AllBrokers: BrokerModel[] = [];
  public filteredBroker: BrokerModel[] = [];
  public brokerSelected: BrokerModel = BrokerModel.EmptyNew();
  public avatarUrl = '';

  @ViewChild('selectBroker', {static: true}) sb: ComboBoxComponent;
  @ViewChild('brokerReward', {static: true}) br: BrokerRewardComponent;

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

  ngOnInit(): void {
    this.ps.getBrokerList('').subscribe(
      resp => {
        this.AllBrokers = resp.List;
        this.onFilterBroker('');
        this.sb.toggle(true);
      }
    );
  }

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

  public onFilterBroker(hint: string): void {
    if ( hint === undefined || hint.length === 0 ) {
      this.filteredBroker = this.AllBrokers.slice(0);
    }else {
      this.filteredBroker = this.AllBrokers.filter(
        v => v.Display.toLowerCase().includes(hint.toLowerCase())
      );
    }
  }

  public onBrokerSelected(broker: BrokerModel): void {
    if ( broker === undefined)  {
      this.avatarUrl = '';
      this.br.ShowBroker('some-broker-that-not-exist');
      this.sb.toggle(true);
    }else {
      this.avatarUrl = 'url(' + this.auth.getUrl('avatar/' + broker.Id) + ')';
      this.br.ShowBroker(broker.Id);
    }
  }

  public validBrokerSelected(): boolean{
    return this.brokerSelected !== undefined && this.brokerSelected.Id !== '';
  }
}

