import {Component, OnInit, Input, ViewEncapsulation, TemplateRef, ViewChild, Output, EventEmitter} from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { Router, ActivatedRoute } from '@angular/router';
import { LocalStorageService } from 'angular-2-local-storage';
import { NavBarService } from '../../ta/ta.service';
import 'rxjs/Rx' ;
import { environment } from '../../../environments/environment.dev';

@Component({
  selector: 'app-candidate-newdetail',
  templateUrl: './candidate-newdetail.component.html',
  styleUrls: ['./candidate-newdetail.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class CandidateNewdetailComponent implements OnInit {

  @Input() canDetail: any;
  @Input() empData: any;
  @Output() editCandInfo = new EventEmitter<any>();

  details: any;
  image: any;
  pgInitiate: boolean = false;
  loggedInUserRole: string;
  imgPath = environment.imageUrl+"/assets/img/";
  imgLd = environment.imageUrl+"/assets/images/";
  candidateLevel: string;
  feedbackDets: any;
  filterActive = 'S2';
  primaryCompleted: boolean = false;
  priExtraLbl: boolean = false;
  codExtraLbl: boolean = false;
  whitExtraLbl: boolean = false;
  leadExtraLbl: boolean = false;
  fedBck: any = {};
  selectModalValue: any;
  coaches = [];
  assessments = [];
  FBmodal:boolean;
  assessmentSelected :any;
  coachSelected : any;
  onSelectedCandidate = [];
  loggedInUser: any;
  UserID: number;
  candInfoDts: any;
  modalUserId:any;
  modalStatus:any;
  modalModal:any;
  modalData:any;
  editCanCopy: boolean = false;
  resFile: any;
  contType:any;
  candResume: any;
  isBtnNotActive:boolean = false;
  workspcId = {};
  awsDets: any;
  workSpaceSuccess: boolean = false;
  registrationCode: any;
  loaderImg: boolean = false;
  candWhiteCrDt: any;
  candWhiteUpDt: any;
  candLeaderCrDt: any;
  candLeaderUpDt: any;
  chalNotIntd:boolean = false;
  imageUrl: string = environment.imageUrl;
  
  constructor(protected localStorageService: LocalStorageService,
    private AuthService: AuthService,
    private router: Router,
    private route: ActivatedRoute,
    private toastr: ToastsManager,
    private navBarService: NavBarService,
  ) { 
    // this.getCandfeedback();
    this.empData = this.localStorageService.get('userInfo');
  }

  ngOnInit() {
    this.editCandInfo.emit(this.canDetail.infoMstr.userInfoMstrId);
    // console.log(JSON.stringify(this.canDetail));
    console.log("empData", this.empData);
    this.loggedInUserRole = this.localStorageService.get('userSession');
    this.UserID = this.canDetail.infoMstr.userInfoMstrId;
    if(this.canDetail.infoMstr.status == 'ONBOARDED'){
      // this.candidateLevel = 'Candidate Mettl';
      // this.getCandfeedback();
      this.pgInitiate = true;
    }
    else if((this.canDetail.infoMstr.status == 'METTL_INITIATED')|| (this.canDetail.infoMstr.status == 'METTL_IN_PROGRESS') || (this.canDetail.infoMstr.status == 'METTL_FAILED') || (this.canDetail.infoMstr.status == 'METTL_REVIEW')){
      // this.candidateLevel = 'Candidate Mettl';
      // this.getCandfeedback();
      this.pgInitiate = false;
      this.primaryCompleted = false;
      this.priExtraLbl = true;
      this.codExtraLbl = false;
      this.whitExtraLbl = false;
      this.leadExtraLbl = false;
    }
    else if((this.canDetail.infoMstr.status == 'METTL_CLEARED') ||  (this.canDetail.infoMstr.status == 'CODING_CHALLENGE_READY') || (this.canDetail.infoMstr.status =='CODING_CHALLENGE_INITIATED') || (this.canDetail.infoMstr.status == 'CODING_CHALLENGE_STARTED') || (this.canDetail.infoMstr.status == 'CODING_CHALLENGE_COMPLETED') || (this.canDetail.infoMstr.status == 'CODING_CHALLENGE_REJECTED')){
      // this.candidateLevel = 'Candidate Coding Challenge';
      // this.getCandfeedback();
      this.pgInitiate = false;
      this.primaryCompleted = true;
      this.priExtraLbl = false;
      this.codExtraLbl = true;
      this.whitExtraLbl = false;
      this.leadExtraLbl = false;
      this.stepC2();
    }
    else if( (this.canDetail.infoMstr.status == 'CODING_CHALLENGE_CLEARED') || (this.canDetail.infoMstr.status == 'WHITEBOARD_READY') ||  (this.canDetail.infoMstr.status == 'WHITEBOARD_REJECTED')){
      // this.candidateLevel = 'Candidate Whiteboard';
      // this.getCandfeedback();
      this.pgInitiate = false;
      this.primaryCompleted = true;
      this.priExtraLbl = false;
      this.codExtraLbl = false;
      this.whitExtraLbl = true;
      this.leadExtraLbl = false;
      this.stepC3();
    }
    else if((this.canDetail.infoMstr.status == 'WHITEBOARD_CLEARED') || (this.canDetail.infoMstr.status == 'LEADERSHIP_CONNECT_READY') || (this.canDetail.infoMstr.status == 'LEADERSHIP_CONNECT_CLEARED') || (this.canDetail.infoMstr.status == 'LEADERSHIP_CONNECT_REJECTED')){
      // this.candidateLevel = 'Candidate Leadership Connect';
      // this.getCandfeedback();
      this.pgInitiate = false;
      this.primaryCompleted = true;
      this.priExtraLbl = false;
      this.codExtraLbl = false;
      this.whitExtraLbl = false;
      this.leadExtraLbl = true;
      this.stepC4();
    }

    // if(this.priExtraLbl){
    //   this.candidateLevel = 'Candidate Mettl';
    //   this.getCandfeedback();
    // }else if(this.codExtraLbl){
    //   this.candidateLevel = 'Candidate Coding Challenge';
    //   this.getCandfeedback();
    // }else if(this.whitExtraLbl){
    //   this.candidateLevel = 'Candidate Whiteboard';
    //   this.getCandfeedback();
    // }else if(this.leadExtraLbl){
    //   this.candidateLevel = 'Candidate Leadership Connect';
    //   this.getCandfeedback();
    // }

    if(this.priExtraLbl){
      this.candidateLevel = 'Candidate Mettl';
      this.getCandfeedback();
    }else if(this.codExtraLbl){
      this.candidateLevel = 'Candidate Coding Challenge';
      this.getCandfeedback();
    }else if(this.whitExtraLbl){
      this.candidateLevel = 'Candidate Whiteboard';
      this.getCandfeedback();
    }else if(this.leadExtraLbl){
      this.candidateLevel = 'Candidate Leadership Connect';
      this.getCandfeedback();
    }

    if(this.canDetail.eventDetails){
      this.canDetail.eventDetails.forEach(element => {
        if(element.pgEventRule.eventRuleName == "Candidate Whiteboard"){
          this.candWhiteCrDt = element.createdDt;
          this.candWhiteUpDt = element.updatedDt;
        }
        if(element.pgEventRule.eventRuleName == "Candidate Leadership Connect"){
          this.candLeaderCrDt = element.createdDt;
          this.candLeaderUpDt = element.updatedDt;
        }
      });
    }
  }

  getCandImageDetails() {
    // this.employeeHttpService.getCandidateImage(this.canDetail.candidateDetails.userInfoMstrId).takeUntil(this.$destroyed)
    //   .subscribe(data => {
    //     if (data === undefined || data.length === 0) {
    //       this.image = '';
    //     } else {
    //       this.image = 'data:image/jpg;base64,' + data[0].fileContent;
    //     }
    //   });
  }

  getCandfeedback(){
    console.log("candidateLevel -- ", this.candidateLevel);
    if(this.candidateLevel == 'Candidate Mettl'){
       this.candidateLevel = "PC";
    }
    else if(this.candidateLevel == 'Candidate Coding Challenge'){
        this.candidateLevel = "CC";
    }
    else if(this.candidateLevel == 'Candidate Whiteboard'){
      this.candidateLevel = "WC";
    }
    else if(this.candidateLevel == 'Candidate Leadership Connect'){
      this.candidateLevel = "LC";
    }
    console.log("upadted candidateLevel -- ", this.candidateLevel);
    this.AuthService.getCandidateFeedback(this.canDetail.infoMstr.userInfoMstrId,this.candidateLevel).then(resp => {
      if(resp.errorBean && resp.errorBean.errorCode){
        this.toastr.error(resp.errorBean.errorMessage);
      }
      else{
        this.feedbackDets = resp.candidateFeedbacks;
        console.log("feedbackDets", JSON.stringify(this.feedbackDets));
      }
    }).catch(err => {
      console.log(err, 'error')
    })
  }

  getInitials(fullName: string) {
    if (fullName) {
      return fullName.replace(/\W*(\w)\w*/g, '$1').toUpperCase();
    }
  }

  downloadCandResume(id){
    console.log("candidate resume file id -- ", id);
    this.AuthService.getFile(id).then(res =>{
      console.log(res)
      this.resFile = res[0].fileName;
      this.contType = res[0].contentType;
      this.candResume = res[0].fileContent;
      //this.downlaodFile(this.resFile, this.contType, this.candResume);
      let url = 'data:'+res[0].contentType+';base64,'+res[0].fileContent;
      var a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display: none');
      a.href = url;
      a.download = res[0].fileName;
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove(); 

    })
  }

  // downlaodFile(filename, cType, data){
  //   var blob = new Blob([data], { type: cType });
  //   var url= window.URL.createObjectURL(blob);
  //   // window.open(url);
  //   var a = document.createElement('a');
  //   document.body.appendChild(a);
  //   a.setAttribute('style', 'display: none');
  //   a.href = url;
  //   a.download = filename;
  //   a.click();
  //   window.URL.revokeObjectURL(url);
  //   a.remove(); // remove the element
  // }

  invitePl(){
    if(!this.empData.email){
      this.empData.email = this.empData.emailId;
    }
    let reqJson = {
      "candidateIds": [this.canDetail.infoMstr.userInfoMstrId],
      "loggedInUser": this.empData.email
    }
    this.AuthService.getInvite(reqJson).then(responseData => {
      console.log(responseData)
      // this.step1();
      if(responseData.status == 'success'){
        this.toastr.success(responseData.message);
        this.getUpdCandDet(this.canDetail.infoMstr.userInfoMstrId);
      }
      else{
        this.toastr.error(responseData.message)
      }
    }).catch(err => {
      console.log(err);
      this.toastr.error(err.message)
    })
  }

  getUpdCandDet(id){
    this.AuthService.getCandDetails(id).then(resp => {
      this.canDetail = resp;
      console.log("response", JSON.stringify(this.canDetail));
      if(this.canDetail.infoMstr.status == 'METTL_INITIATED'){
        this.pgInitiate = false;
        this.priExtraLbl = true;
      }else if(this.canDetail.infoMstr.status == 'CODING_CHALLENGE_READY') {
        this.pgInitiate = false;
        this.codExtraLbl = true;
        this.filterActive = 'S3';
      }else if(this.canDetail.infoMstr.status == 'WHITEBOARD_READY') {
        this.pgInitiate = false;
        this.whitExtraLbl = true;
        this.filterActive = 'S4';
      }
    }).catch(err => {
      console.log(err, 'error')
    })
  }

  getStatus(type) {
    const  status = {
      'METTL_INITIATED': 'To Do',
      'METTL_IN_PROGRESS': 'Inprogress',
      'METTL_CLEARED': 'Done',
      'METTL_FAILED':'Reject',
      'METTL_REVIEW':'Review',
      'CODING_CHALLENGE_READY':'Review',
      'CODING_CHALLENGE_INITIATED':'To Do',
      'CODING_CHALLENGE_STARTED': 'Inprogress',
      'CODING_CHALLENGE_COMPLETED': 'Done',
      'CODING_CHALLENGE_REJECTED': 'Reject',
      'CODING_CHALLENGE_CLEARED': 'Done',
      'WHITEBOARD_READY': 'Inprogress',
      'WHITEBOARD_CLEARED': 'Done',
      'WHITEBOARD_REJECTED':'Reject',
      'LEADERSHIP_CONNECT_READY': 'Inprogress',
      'LEADERSHIP_CONNECT_CLEARED': 'Done',
      'LEADERSHIP_CONNECT_REJECTED':'Reject',
      'default':'Invalid'
    };
    return status[type] || status['default'];
  }

  getcolor(x) {
    const status = x;
    let color = '';
    switch (status) {
      case 'Review':
        color = '#E7B01D';
        return color;
      case 'To Do':
        color = '#1ED0CB';
        return color;
      case 'Done':
        color = '#16C48A';
        return color;
      case 'Inprogress':
        color = '#1AB7F6';
        return color;
      case 'Reject':
        color = '#D9816A';
        return color;
      default:
        color = '#ffffff';
        return color;
    }
  }

  stepC1(){
    this.chalNotIntd = false;
    this.filterActive = "S2";
    this.candidateLevel = 'Candidate Mettl';
    let txt = this.canDetail.eventDetails.findIndex((obj => obj.eventName == this.candidateLevel));
    if(txt >= 0){
      this.chalNotIntd = false;
    }
    else{
      this.chalNotIntd = true;
    }
    console.log(this.canDetail.eventDetails);
    this.getCandfeedback();
  }

  stepC2(){
    console.log("Cand Status is  --- ", this.canDetail.infoMstr.status);
    this.chalNotIntd = false;
    this.filterActive = "S3";
    this.candidateLevel = 'Candidate Coding Challenge';
    let txt = this.canDetail.eventDetails.findIndex((obj => obj.eventName == this.candidateLevel));
    if(txt >= 0){
      this.chalNotIntd = false;
    }
    else{
      this.chalNotIntd = true;
    }
    
    if((this.canDetail.infoMstr.status == 'CODING_CHALLENGE_READY') ||(this.canDetail.infoMstr.status == 'CODING_CHALLENGE_INITIATED') || (this.canDetail.infoMstr.status == 'CODING_CHALLENGE_STARTED') || (this.canDetail.infoMstr.status == 'CODING_CHALLENGE_COMPLETED') || (this.canDetail.infoMstr.status == 'CODING_CHALLENGE_REJECTED')){
      // this.codExtraLbl = true;
      this.filterActive = "S3";
      this.candidateLevel = 'Candidate Coding Challenge';
      console.log("s3 --- ",this.candidateLevel);
    }
    this.getCandfeedback();
  }

  stepC3(){
    console.log("Cand Status is  --- ", this.canDetail.infoMstr.status);
    this.filterActive = "S4";
    this.candidateLevel = 'Candidate Whiteboard';
    this.chalNotIntd = false;
    let txt = this.canDetail.eventDetails.findIndex((obj => obj.eventName == this.candidateLevel));
    if(txt >= 0){
      this.chalNotIntd = false;
    }
    else{
      this.chalNotIntd = true;
    }
    if( (this.canDetail.infoMstr.status == 'CODING_CHALLENGE_CLEARED') || (this.canDetail.infoMstr.status == 'WHITEBOARD_READY') ||(this.canDetail.infoMstr.status == 'WHITEBOARD_REJECTED')){
      // this.codExtraLbl = true;
      this.filterActive = "S4";
      this.candidateLevel = 'Candidate Whiteboard';
      console.log("s4 --- ",this.candidateLevel);
    }
    this.getCandfeedback();
  }

  stepC4(){
    console.log("Cand Status is  --- ", this.canDetail.infoMstr.status);
    this.filterActive = "S5";
    this.candidateLevel = 'Candidate Leadership Connect';
    this.chalNotIntd = false;
    let txt = this.canDetail.eventDetails.findIndex((obj => obj.eventName == this.candidateLevel));
    if(txt >= 0){
      this.chalNotIntd = false;
    }
    else{
      this.chalNotIntd = true;
    }
    if( (this.canDetail.infoMstr.status == 'WHITEBOARD_CLEARED') || (this.canDetail.infoMstr.status == 'LEADERSHIP_CONNECT_CLEARED') || (this.canDetail.infoMstr.status == 'LEADERSHIP_CONNECT_REJECTED')){
      // this.codExtraLbl = true;
      this.filterActive = "S5";
      this.candidateLevel = 'Candidate Leadership Connect';
      console.log("s5 --- ",this.candidateLevel);
    }
    this.getCandfeedback();
  }

  submitFeedback(){
    this.fedBck.level = this.candidateLevel;
    this.fedBck.reviewDate = new Date().toISOString();
    this.fedBck.reviewedBy = this.empData.userInfoMstrId;
    this.fedBck.userId = this.canDetail.infoMstr.userInfoMstrId;
    console.log(this.fedBck);
    this.AuthService.submitCandFeedback(this.fedBck).then(resp => {
      //console.log(resp, 'response')
      if (resp.successMessage == 'Record has been inserted') {
        this.toastr.success('Feedback submitted successfully');
        this.fedBck = {};
        this.getCandfeedback();
      }
      else {
        this.toastr.error(resp.errorBean.errorMessage);
      }
    }).catch(err => {
      console.log(err, "Error")
      this.toastr.error(err);
    })
  }

  addEditCoachRUc(e){
    document.getElementById('coachUseCseModalButton').click();
    this.selectModalValue = e;
    console.log(this.selectModalValue);
    console.log("loggin In user ID -- ", this.empData.userInfoMstrId);
    this.FBmodal = false;
    if(this.selectModalValue === 'coach') {
      this.AuthService.getAllCoachesforPgm(this.empData.userInfoMstrId).then(resp => {
        this.coaches = resp;
        // document.getElementById('openModalButton').click();

      }).catch(err => {
        console.log(err);
      })
     } else {
      this.AuthService.getAllAssessmentforPgm(this.empData.userInfoMstrId).then(resp => {
        // this.assessments = resp.businessUseCase.useCaseList.concat(resp.technicalUseCase.useCaseList);
        if(resp.businessUseCase.useCaseList && resp.technicalUseCase.useCaseList)
        {  
          this.assessments = resp.businessUseCase.useCaseList.concat(resp.technicalUseCase.useCaseList);
        }
        else if(resp.businessUseCase.useCaseList){
          this.assessments = resp.businessUseCase.useCaseList;
        } 
        else if(resp.technicalUseCase.useCaseList){
          this.assessments =resp.technicalUseCase.useCaseList;
        }
        console.log(this.assessments);
        // document.getElementById('openModalButton').click();

      }).catch(err => {
        console.log(err);
      })
    }
  }


  selectedCoach(data){
    console.log(data);
    this.coachSelected = data

    this.onSelectedCandidate = [];
    this.onSelectedCandidate.push(this.canDetail.infoMstr.userInfoMstrId)
    // this.empList.forEach(usr => {
    // })

  }
  selectedAssess(data){
    console.log(data);
    this.assessmentSelected = data;
    this.onSelectedCandidate = [];
    this.onSelectedCandidate.push(this.canDetail.infoMstr.userInfoMstrId)
    

  }
  submitCoachUpdate(){
    if(this.empData.email){
      this.loggedInUser = this.empData.email;
    }
    else{
      this.loggedInUser = this.empData.emailId;
    }
    var reqJson = {
    "id": this.coachSelected,
    "loggedInUser": this.loggedInUser,
    "userInfoMstrIds": this.onSelectedCandidate,
    }
    console.log(reqJson);
    this.AuthService.getUpdateCoach(reqJson,'CC').then(resp => {
      console.log(resp);
      if(resp.status === 'success'){
        this.toastr.success(resp.message);
        this.closeModal();
        this.getCandUpdDets();
      } else {
        this.toastr.error(resp.message)
      }
    }).catch(err => {
      console.log(err);
    })
  }

  submitAssessmentUpdate(){
    if(this.empData.email){
      this.loggedInUser = this.empData.email;
    }
    else{
      this.loggedInUser = this.empData.emailId;
    }
    var reqJson = {
      "id": this.assessmentSelected,
      "loggedInUser": this.loggedInUser,
      "userInfoMstrIds": this.onSelectedCandidate,
    }
    console.log(reqJson);
    this.AuthService.getUpdateAssessment(reqJson).then(resp => {
      console.log(resp);
      if(resp.status === 'success'){
        this.toastr.success(resp.message);
        this.closeModal();
        this.getCandUpdDets();
      } else {
        this.toastr.error(resp.message)
      }
    }).catch(err => {
      console.log(err);
    })
  }

  closeModal()
  {
    console.log('closeModal');
    document.getElementById('closeAssignCoachModal').click()
  }

  getCandUpdDets(){
    this.AuthService.getCandDetails(this.UserID).then(resp => {
      this.canDetail = resp;
      console.log("Updated Cand Dets", JSON.stringify(this.canDetail));
    }).catch(err => {
      console.log(err, 'error')
    })
  }

  editCand(id, status){
    console.log(id);
    this.editCandInfo = null;
    this.editCanCopy = false;
    // alert("Functionality yet to be done");
    document.getElementById('canEditBtn').click();
    this.AuthService.getCandidateInfo(id).then(resp => {
      console.log(resp);
      var candRespInfo = resp
      this.candInfoDts = {candInfoDts:candRespInfo, status:status};
      this.editCandInfo = this.candInfoDts;
      this.editCanCopy = true;
    }).catch(err => {
      console.log(err);
    })
  }

  downloadMettlReport(id){

  }

  getScoreVal(){
    let theScore : number;
    theScore = this.canDetail.eventDetails[0].eventScore;
    return theScore;

  }
  candConfirm(id,status,modal,data){
    console.log(id, status, modal, data);
    this.modalStatus = null;
    // this.onfeedBackCC.emit({userId:id,status:status,modal:modal,data:data})

    this.FBmodal = modal;
    document.getElementById('coachUseCseModalButton').click();
    this.modalData = data;
    this.modalUserId =id;
    this.modalModal = modal;
    this.modalStatus = status;
  }

  feedbackSubmit(value){
    var reqJson =  {
      "level": this.candidateLevel,
      "reviewDate": new Date().toISOString(),
      "reviewFeedback": value,
      "reviewedBy": this.empData.userInfoMstrId,
      "userId": this.modalUserId
    }
    console.log(reqJson);
    this.getFeedBack(reqJson)
  }

  getFeedBack(data){

    console.log(data);
    this.AuthService.getFeedBacks(data).then(resp => {
      console.log(resp);
      if(resp.status == 'success') {
       // this.checkTap();

        this.toastr.success('FeedBack submited successfully')
        this.closeModal();
        if(!this.empData.email){
          this.empData.email = this.empData.emailId;
        }
        var reqJson ={
          userIds: [data.userId],
          status: null,
          loggedInUser: this.empData.email,
          eventId: null
        }
        console.log(this.modalData);
        // console.log(reqJson);
        if(this.modalData == "approve"){
          if(this.modalStatus == "METTL_REVIEW"){
            reqJson.status = 'METTL_CLEARED';
            reqJson.eventId = 1;
            this.stepC2();
          }
          else if(this.modalStatus == "CODING_CHALLENGE_COMPLETED"){
              reqJson.status = 'CODING_CHALLENGE_CLEARED';
              reqJson.eventId = 2;
              this.stepC3();
            }
          else if(this.modalStatus == "WHITEBOARD_READY"){
            reqJson.status = 'WHITEBOARD_CLEARED';
            reqJson.eventId = 3;
            this.stepC4();
          }
          else if(this.modalStatus == "WHITEBOARD_CLEARED"){
            reqJson.status = 'LEADERSHIP_CONNECT_CLEARED';
            reqJson.eventId = 4;
          }
          this.updateStatusPC(reqJson);
        }
        else if(this.modalData == "reject"){
          if(this.modalStatus == "METTL_REVIEW"){
            reqJson.status = 'METTL_FAILED';
            reqJson.eventId = 1;
            this.stepC1();
          }
          else if(this.modalStatus == "CODING_CHALLENGE_COMPLETED"){
              reqJson.status = 'CODING_CHALLENGE_REJECTED';
              reqJson.eventId = 2;
              this.stepC2();
            }
          else if(this.modalStatus == "WHITEBOARD_READY"){
            reqJson.status = 'WHITEBOARD_REJECTED';
            reqJson.eventId = 3;
            this.stepC3();
          }
          else if(this.modalStatus == "WHITEBOARD_CLEARED"){
            reqJson.status = 'LEADERSHIP_CONNECT_REJECTED';
            reqJson.eventId = 4;
            this.stepC4();
          }
          this.updateStatusPC(reqJson)
        }
      } else {
        this.toastr.error('Failed to save the details')

      }
    }).catch(err => {
      console.log(err);
    })
  }

  // candMovetoNextLevel(data){
  //     this.AuthService.candidateStatusUpdate(data).then(responseData => {
  //       let resp = responseData;
  //       console.log("new upd  resp -- ", resp);
  //       if(resp.status == 'success'){
  //         this.toastr.success(resp.status);
  //         this.updateStatusPC(data);
  //       }
  //       else{
  //         this.toastr.error(resp.status);
  //       }
  //     })
  // }

  updateStatusPC(data){
    console.log(333333);
    this.AuthService.getUpdateCandidateStatus(data).then(responseData => {
      // this.AuthService.candidateStatusUpdate(data).then(responseData => {
      console.log(responseData)
      if(responseData.status == 'success') {
        this.loaderImg = false;
        this.isBtnNotActive = false;
        this.toastr.success(responseData.message);
        this.refreshCandDets(this.UserID);
      } else {
        this.toastr.error(responseData.message);
        this.isBtnNotActive = false;
        this.loaderImg = false;
      }
      
    }).catch(err => {
      console.log(err)
    })

  }

  refreshCandDets(e){
    console.log(e);
    this.closeEditModal();
    this.getCandUpdDets();
  }

  closeEditModal(){
    document.getElementById("closeEditCandModal").click();
  }

  initiateCodFn(status){
    this.isBtnNotActive = true;
    this.loaderImg = true;
    if(!this.empData.email){
      this.empData.email = this.empData.emailId;
    }
    let reqJson ={
      userIds: [this.UserID],
      status: status,
      loggedInUser: this.empData.email,
      eventId: 2
    }
    this.AuthService.getUserInfoBy({adId:this.canDetail.infoDetails.adId}).then(resp => {
      console.log(resp,'getWorkspaceErr')
      let resPayload = resp
      if(resp.status == 'success') {
        var workSpaceData = JSON.parse(resPayload['data'])
        console.log(workSpaceData);
        this.AuthService.setupWorkSpace({sname:workSpaceData.adId,sbundleId:workSpaceData.bundleId,sdirId:workSpaceData.directoryId}).then(wsResp => {
          console.log(wsResp,'workSpace Response');
          if(wsResp.status == 'error') {
            this.toastr.error(wsResp.message)
          }
          else {
            this.updateStatusPC(reqJson)
          }
        }).catch(wsErr => {
          console.log(wsErr,'workSpace Error')
        })
      }
      else {
        //console.log(this.respData)
      }
    }).catch(getWorkspaceErr => {
      console.log(getWorkspaceErr,'getWorkspaceErr')
    })
  }

  getAwsCreds(ADID) {
    this.workspcId = {
      'adId': ADID
    };
    this.AuthService.getWorkspaceId(this.workspcId).then(resp => {
      if (resp.status === 'success') {
        this.awsDets = JSON.parse(resp['data']);
        console.log(this.awsDets);
        this.workSpaceSuccess = true;
        this.registrationCode = this.awsDets.registrationCode;
      }
      else {
        console.log('workspaceId couldnot be retrieved');
        this.toastr.error('AWS Credentials could not be retrieved !!')
      }
    }).catch(err => {
      console.log(err);
      this.toastr.error(err);
      setTimeout(() => {
      },6000);
    });
  }
}
