import {Component, EventEmitter, Input, OnInit, Output, QueryList, ViewChild, ViewChildren, AfterViewInit} from '@angular/core';
import {LoanModel} from '../models/loan.model';
import {PeopleService} from '../service/people.service';
import {PeopleModel} from '../models/people.model';
import {AuthService} from '../service/auth.service';
import {ClonerService} from '../service/clone.service';
import {BrokerModel} from '../models/broker.model';
import {PeopleMapModel} from '../models/people-map.model';
import {ComboBoxComponent, PreventableEvent} from '@progress/kendo-angular-dropdowns';
import {FormGroup} from '@angular/forms';

@Component({
  selector: 'app-loan-edit-people',
  templateUrl: './loan-edit-people.component.html',
  styleUrls: ['./loan-edit-people.component.scss']
})
export class LoanEditPeopleComponent implements OnInit, AfterViewInit {
  @Input() public Loan: LoanModel;
  @Output() public NotifyNext = new EventEmitter<boolean>();
  @Output() public NotifyPrev = new EventEmitter<boolean>();
  @Output() public errorOccurred = new EventEmitter<string>();
  @ViewChildren(ComboBoxComponent) cb!: QueryList<ComboBoxComponent>;
  @ViewChild('form', {static: true}) form: FormGroup;

  public AllPeople: PeopleModel[];
  public AllBrokers: BrokerModel[];
  public role: any = {}; // string to string map
  public roles = ['Admin', 'Referral', 'Observer', 'Verifier', 'Ex-Broker', 'Ex-Client', 'Banned', 'Unknown'];

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

  public virtual: any = {
    itemHeight: 28
  };

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

    this.ps.getBrokerList('').subscribe(
      resp => {
          this.AllBrokers = resp.List;
      }
    );

    // ensure role strings are available for selection
    this.Loan.PeopleMap.forEach( v => {
      if ( v.Role.toLowerCase() !== 'client' && v.Role.toLocaleLowerCase() !== 'broker'){
        this.roles.push( v.Role);
        this.roles = [...new Set(this.roles)]; // remove duplicates
        this.role[v.PeopleId] = v.Role;
      }
    });
  }

  ngAfterViewInit(): void {
      this.cb.changes.subscribe( (data: QueryList<ComboBoxComponent> ) => {
         data.forEach( v => {
           if (v.value === undefined && !v.isOpen) {
             v.toggle(true);
           }
         });
      });
  }


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

  public next(): void{
    const err = this.rebuildPeopleMap(null);
    if (err) {
      this.showError('Please Select The people\'s role');
      return;
    }

    if ( this.Loan.Client.length === 0) {
      this.showError('Please Select at least 1 client');
      return;
    }

    if ( this.Loan.Broker.length === 0) {
      this.showError('Please Select at least 1 Broker');
      return;
    }

    this.ps.syncPeople(this.Loan.cloneForJson()).subscribe( resp => {});
    this.NotifyNext.emit(true);
  }

  public prev(): void {
    this.NotifyPrev.emit(true);
  }

  public rebuildPeopleMap(event: PreventableEvent): boolean{
    this.Loan.PeopleMap = [];
    this.Loan.Client.forEach(v => {
      this.Loan.PeopleMap.push(new PeopleMapModel(
        this.Loan.Id,
        'Client',
        v.Id
      ));
    });

    this.Loan.Broker.forEach(v => {
      this.Loan.PeopleMap.push(new PeopleMapModel(
        this.Loan.Id,
        'Broker',
        v.Id
      ));
    });

    let err = false;
    this.Loan.OtherRewarder.forEach(v => {
      if (this.role[v.Id] === undefined){
        err = true;
      }
      this.Loan.PeopleMap.push(new PeopleMapModel(
        this.Loan.Id,
        this.role[v.Id] || 'Unknown',
        v.Id
      ));
    });

    return err;
  }

  public showError(err: string): void {
    this.errorOccurred.emit(err);
  }
}
