import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { ContactsService } from 'src/app/services/contacts.service';
import { EventPerson } from 'src/app/models/eventperson.model';
import { removeDuplicate } from 'src/plugin/removeDuplicate.js'
import { ThemeService } from 'src/app/services/theme.service'

@Component({
  selector: 'app-attendee-modal',
  templateUrl: './attendee-modal.page.html',
  styleUrls: ['./attendee-modal.page.scss'],
})
export class AttendeePage implements OnInit {

  // Defined by the API
  contacts: EventPerson[];
  showLoader: boolean = false;
  eventPersons: EventPerson[];


  @Output() closeComponent = new EventEmitter<any>();

  @Output() setIntervenient = new EventEmitter<any>();
  @Output() setIntervenientCC = new EventEmitter<any>();
  @Output() dynamicSetIntervenient = new EventEmitter<any>();


  @Input() taskParticipants:EventPerson[] = [];
  @Input() taskParticipantsCc:EventPerson[] = [];

  @Input() footer: boolean;

  LtaskParticipants: EventPerson[] = [];
  LtaskParticipantsCc: EventPerson[] = [];

  constructor(
    private modalCtrl: ModalController, 
    private contactsService: ContactsService,
    public ThemeService: ThemeService ) { 

      this.LtaskParticipants  = removeDuplicate(this.taskParticipants);
      this.LtaskParticipantsCc = removeDuplicate(this.taskParticipantsCc);
    }

  ngOnChanges(){
    this.LtaskParticipants  = removeDuplicate(this.taskParticipants);
    this.LtaskParticipantsCc = removeDuplicate(this.taskParticipantsCc);
  }
  
  currentPath = window.location.pathname;
  @Input() adding: "intervenient" | "CC";

  ngOnInit() {

    this.fetchContacts("");
    
    if(this.LtaskParticipants == null || this.LtaskParticipants == undefined) {
      this.LtaskParticipants = [];
    }

    if(this.LtaskParticipantsCc == null || this.LtaskParticipantsCc == undefined) {
      this.LtaskParticipantsCc = [];
    }

  }
  

  save() {

    this.setIntervenient.emit(removeDuplicate(this.LtaskParticipants));
    this.setIntervenientCC.emit(removeDuplicate(this.LtaskParticipantsCc));

    this.closeComponent.emit();
  }

  setContactWithClose() {

    if(this.currentPath == '/home/gabinete-digital') {
      console.log('set!!!!! ')
      this.setIntervenient.emit(this.LtaskParticipants);
      this.setIntervenientCC.emit(this.LtaskParticipantsCc);
    } 

    /* console.log('data', this.LtaskParticipants, this.LtaskParticipantsCc ); */
    this.dynamicSetIntervenient.emit({
      taskParticipants: this.LtaskParticipants,
      taskParticipantsCc: this.LtaskParticipantsCc
    })

  }

  async selectContact(itm: EventPerson){

    if(this.adding == "intervenient") {

      itm.IsRequired = true;
      this.LtaskParticipants.push(itm);
      
    } else if (this.adding == "CC") {
      
      itm.IsRequired = false;
      this.LtaskParticipantsCc.push(itm);
    } else {
      // console.log('bug')
    }
    
    // run only in gabinete digital

    this.setContactWithClose();
  }

  close(){
    this.closeComponent.emit();
  }

  onChange(evt: any) {
    this.fetchContacts(evt.detail.value);
  }

  filterSearchList(itm: EventPerson): boolean {

    const result = this.LtaskParticipants.concat(this.LtaskParticipantsCc).find((contact, index)=>{
      
      if(contact.Name.toLowerCase() == itm.Name.toLowerCase() && contact.EmailAddress.toLowerCase() == itm.EmailAddress.toLowerCase()){
        index = index;
        return contact;
      }
    });

    // if to show
    if(undefined != result){
      return false;
    }
    

    const result2 = this.LtaskParticipantsCc.find((contact, index)=>{
      
    if(contact.Name.toLowerCase() == itm.Name && contact.EmailAddress.toLowerCase() == itm.EmailAddress.toLowerCase()){
        index = index;
        return contact;
      }
    });

    // if to show
    if(undefined != result2){
      return false;
    }
    
    // don't show
    return true;
    
  }

  remove(itm: EventPerson){

    if(this.adding == "intervenient"){

      this.LtaskParticipants = this.LtaskParticipants.filter((contact, index) =>{

        if(contact.Name.toLocaleLowerCase() != itm.Name.toLocaleLowerCase() && contact.EmailAddress.toLocaleLowerCase() != itm.EmailAddress.toLocaleLowerCase()){
          return contact;
        }
        return false;
  
      });

    } else if (this.adding == "CC") {

      this.LtaskParticipantsCc = this.LtaskParticipantsCc.filter((contact, index) =>{

        if(contact.Name.toLocaleLowerCase() != itm.Name.toLocaleLowerCase() && contact.EmailAddress.toLocaleLowerCase() != itm.EmailAddress.toLocaleLowerCase()){
          return contact;
        }
        return false;
  
      });

    }
    this.setContactWithClose();
  
  }



  async fetchContacts(filter: string) {
    this.showLoader = true;

    this.contactsService.getContacts(filter).subscribe(result =>
      {
        if (this.eventPersons != null)
        {
          this.eventPersons.forEach(attendee => {
            const index: number = result.findIndex((cont) => {
              return cont.EmailAddress.toLowerCase() == attendee.EmailAddress.toLowerCase()
            });
  
            result.splice(index, 1);
          });
        }

        this.contacts = result;
        this.showLoader = false;
      }
    );
  }

}