import { Component, OnInit, EventEmitter, Output, Input, HostListener, OnChanges, SimpleChanges, ViewChild, ElementRef } from '@angular/core';
import { PgUserInfoDtlsList, PgEmployeeProjectDtlsEntity, PgUserInfoMstr, EmployeeDetailsResponse } from 'app/models/employee.model';
import { EmployeeHttpService } from 'app/services/employee/employee-http.service';
import { LocalStorageService } from 'angular-2-local-storage';
import { ToastsManager } from 'ng2-toastr';
import { FormsModule } from '@angular/forms';
import { environment } from '../../../../../environments/environment.dev';


interface Skill {
  text: string;
  selected: boolean;
  id: number;
}

@Component({
  selector: 'app-card-details',
  templateUrl: './card-details.component.html',
  styleUrls: ['./card-details.component.scss']
})
export class CardDetailsComponent {
  listSkills: { text: any; selected: boolean; id: any; }[];
  UserInfoDtls: PgUserInfoDtlsList;
  applyRoleButtonApplyForCoach = false;
  backupSkillsSelected: Skill[] = [];
  public showDropdownList = true;
  showApplyForCoach = false;
  localUserInfoMstr: PgUserInfoMstr;
  isEditForm: boolean;
  userInfo: any;
  projectDetails = [];
  imageUrl: string = environment.imageUrl;
  @Output() navigation = new EventEmitter<{ page: string, data?: any }>();
  private _projects: PgEmployeeProjectDtlsEntity[];
  private _data: { UserInfoDtls: PgUserInfoDtlsList, listSkills: Skill[], showApplyForCoach: boolean };
  @Input()
  set data(value) {

    this._data = value;
    if (this._data.listSkills && this._data.UserInfoDtls) {

      this.localSkills = Array.from(this._data.listSkills);

      this.localUserInfoMstr = this._data.UserInfoDtls.pgUserInfoMstr;

      this._projects = this.data.UserInfoDtls.pgUserInfoMstr.pgEmployeeProjectDtls;

      this.loadProjects(this._projects);

      const skillsOnwerEmployee = this.localUserInfoMstr.pgUserSkillMapping
        .map(s => s.pgSkillTrackDtls.skillTrackDtlsId);

      skillsOnwerEmployee.forEach(skSelected => {
        this.localSkills.forEach(sk => {
          if (skSelected === sk.id) {
            sk.selected = true;
          }
        });
      });

      this.backupSkillsSelected = this.localSkills && Array.from(this.localSkills.filter(s => s.selected)) || [];

      this.applyRoleButtonApplyForCoach = this.data.showApplyForCoach;
    }


  }
  get data() {
    return this._data;
  }
  @Input()
  set projects(value) {
    if (value) {
      this._projects = value;
    }
  }
  get projects() {
    return this._projects;
  }
  localSkills: Skill[] = [];
  @ViewChild('editButton') buttonEdit: ElementRef;
  @HostListener('body:click')
  autoSaveForm() {
    if (this.isEditForm) {
      this.buttonEdit.nativeElement.click();
    }
  }

  constructor(private employeeService: EmployeeHttpService, protected localStorageService: LocalStorageService, private toastr: ToastsManager,
  ) { }


  private loadProjects(p: PgEmployeeProjectDtlsEntity[]) {
    this.projectDetails = p.map(project => {
      return {
        id: project.pgEmployeeProjectDtlsId,
        title: project.title,
        description: project.description,
        skills: project.pgprojectSkillsMapping.map(t => {
          return {
            id: t.pgSkillTrackDtls.skillTrackDtlsId,
            name: t.pgSkillTrackDtls.skillTrackDtlsName
          };
        })
      };
    }).sort((a, b) => {
      return b.id - a.id;
    });
  }


  formSubmit(e) {
    this.isEditForm = !this.isEditForm;
    if (this.isEditForm === false) {
      const form = e.currentTarget as HTMLFormElement
        , fd = new FormData(form);
      if (+fd.get('phone') !== +this.localUserInfoMstr.mobileNo) {

        this.employeeService.updateEmployeeDetails({
          email: this.localUserInfoMstr.emailId,
          firstName: this.localUserInfoMstr.firstNm,
          lastName: this.localUserInfoMstr.lastNm,
          locationId: this.localUserInfoMstr.pgLocation.locationId,
          phone: +fd.get('phone'),
          privilegeId: this.localUserInfoMstr.pgRoleUser
            .sort((a, b) => a.pgRolePrivilege.rolePrivilegeId < b.pgRolePrivilege.rolePrivilegeId ? 1 : -1)[0]
            .pgRolePrivilege.rolePrivilegeId,
          skillId: this.localUserInfoMstr.pgUserSkillMapping.map(s => s.pgSkillTrackDtls.skillTrackDtlsId)
        })
          .subscribe(r => {
            this.localUserInfoMstr = r.pgUserInfoDtls.pgUserInfoMstr;
            this.data.UserInfoDtls.pgUserInfoMstr = r.pgUserInfoDtls.pgUserInfoMstr;
            this.toastr.success('Phone number updated successfully');
          }, err => {
            this.toastr.error('Was Wrong to Save Phone');
          });
      }
    }
  }
  addSkillsToogle() {
    this.showDropdownList = !this.showDropdownList;
    if (!this.showDropdownList) {
      const arrId = this.backupSkillsSelected.filter(s => s.selected);
      const localSkillId = this.localSkills.filter(s => s.selected);
      console.log(this.localSkills.filter(s => s.selected))
      // if (!this.localSkills.filter(s => s.selected).every(v =>
      //   arrId.some(fi => fi.id === v.id)
      // )) {
      if(arrId.length !== localSkillId.length || this.backupSkillsSelected.length !== localSkillId.length){  
        this.employeeService.updateSkillForEmployee(this.localUserInfoMstr.emailId,
          this.localSkills.filter(s => s.selected).map(s => s.id))
          .delay(300)
          .subscribe(done => {
            this.toastr.success('Skills Updated Successfully');
            this.backupSkillsSelected = Array.from(this.localSkills.filter(s => s.selected));
          }
          , err => {
            this.localSkills.forEach(s => s.selected = false);

            this.backupSkillsSelected.forEach(backS => {
              this.localSkills.find(s => s.id === backS.id).selected = true;
            });
            // this.toastr.info('Error, try later.');
            this.toastr.error('Save Error Skills');
          });
      }
    }

  }
  assignNavigation(e) {
    e.data = Object.assign(e.data, { navigation: 'card-details' });
    this.navigation.emit(e);
  }
  autoSave(e) {
    if (e) {
      this.addSkillsToogle();
    }
  }
}
