import { Component, OnInit, OnDestroy, Input, ViewEncapsulation } from '@angular/core';
import { AuthService } from '../../services/auth.service';

import { Router, ActivatedRoute } from '@angular/router';
import { LocalStorageService } from 'angular-2-local-storage';
import _ from "lodash";
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { NavBarService } from '../ta.service';
import { TaModalServiceService, MODAL_CONTENT } from 'app/ta/ta-modal-service.service';
import { log } from 'util';
import { Utils } from 'app/utils';
import { ParseErrorLevel } from '@angular/compiler';
import { MAP_CANDIDATE_STATUS, CANDIDATE_STATUS } from 'app/models/candidateStatus';
import {PagerService} from "../../admin/inner-admin-pages/right-admin-panel/user-mgmt/_services/pager.service";
import {IMyDrpOptions} from "mydaterangepicker";
import {WorkspaceService} from "../../services/workspace.service";
import {environment} from "../../../environments/environment.dev";

//Compounent decleration part  here
@Component({
  selector: 'app-ta-dashboard',
  templateUrl: './ta-dashboard.component.html',
  styleUrls: ['./ta-dashboard.component.css'],
  providers: [NavBarService],
  encapsulation: ViewEncapsulation.Emulated

})



export class TaDashboardComponent implements OnInit, OnDestroy
{

  coaches = [];
  assessments = [];
  assessmentSelected :any
  coachSelected : any
  empList = [
    {"userInfoMstrId":22,"fullName":"SARA SHARMA","mailId":"samaSharma@altimetrik.com","adId":"samaSharma","pgExperienceLevel":null},
    {"userInfoMstrId":24,"fullName":"SARA SHARMA","mailId":"testuser2@bnymellon.com","adId":"testuser2","pgExperienceLevel":null},
    {"userInfoMstrId":26,"fullName":"SARA SHARMA","mailId":"testuser21@bnymellon.com","adId":"testuser21","pgExperienceLevel":null},
    {"userInfoMstrId":28,"fullName":"SARA SHARMA","mailId":"testuser23@bnymellon.com","adId":"testuser23","pgExperienceLevel":null},
  ]

  statusList =[]

  myDateRangePickerOptions: IMyDrpOptions = {
    // other options...
    dateFormat: 'dd.mm.yyyy',
    //showClearDateRangeBtn: false,
    inline: false,
  };

  // For example initialize to specific date (09.10.2018 - 19.10.2018). It is also possible
  // to set initial date range value using the selDateRange attribute.

  private model: any = {beginDate: {year: 2018, month: 10, day: 9},
    endDate: {year: 2018, month: 10, day: 19}};

  public candidatesList;
  public listCandidates;
  public filterCandidates;
  public skills = [];
  public masterSkills = [];
  public masterSkillId = [];
  public levels;
  public city;
  public jobTitles;
  page: number = 1;
  userFilter: any = { fullName: '' };
  isRow: number;
  isRows: string;
  reqData: any;
  name: string;
  fullName: string;
  isApprove: boolean;
  selectUser: boolean;
  selected = 'onboard';
  filterActive = 'S1';
  allClass: any;
  allClassColor; any: any;
  pendingClassColor: any;
  selectModalValue: any;
  pendingClass: any;
  inProgressClass: any;
  term: any;
  loader = false;
  filterBtn = true;
  filterBtnStatus = true;
  footerShow = false;
  onSelectedCandidate = [];

  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    emailId: any,
    email: any,
    skills: any,
    location: any
  };

  userIcon: string;
  UserID: string

  img_path = environment.imageUrl+'/assets/img/Taflow/';

  modalContent: string;
  modalCandidate: string;

  FBmodal = true;
  isLoader = true;

  modalUserId:any;
  modalStatus:any;
  modalModal:any;
  modalData:any;
  modalAdId:any;

  rowCopy = [];
  candidateList = []
  candidateListCopy: any = []
  candidateListSearchCopy: any = []
  private subscriptions = [];

  // filters
  levelFilters = [];
  jobFilters = [];
  skillFilters = [];
  locationFilters = [];
  statusFilters = [];
  @Input() backNavClicked: boolean;
  currentPageData: any;
  showFNm: boolean = false;
  // pager object
  pager: any = {};
  // paged items
  rowIndex: number = -1;

  pagedItems: any[];
  usr_img_path = environment.imageUrl+'/assets/img/admin/';
  candDetailPgNew: boolean = false;
  canDetailToShow: any;

  reqJson = {
    experienceLevel: null,
    fromDate:null,
    jobName: null,
    locations: null,
    skills:null,
    toDate:null,
    userInfoMstrId:null
  }

  locations = [];
  expLevels = [];
  jobAssessments = [];

  filterItem = {
    level : [],
    location: [],
    jobId:[],
    status:[],
    statusActive:''
  }


  levelArrow = true
  locationArrow = false
  statusArrow = false
  jobArrow = false

  statusJson =
    {
      METTL_INITIATED:'Initiated',
      METTL_IN_PROGRESS:'In progress',
      METTL_REVIEW:'Onhold',
      METTL_FAILED:'Rejected',

      METTL_CLEARED:'Awaiting Initiation',
      CODING_CHALLENGE_READY:'Awaiting Initiation',
      CODING_CHALLENGE_INITIATED:'Initiated',
      CODING_CHALLENGE_STARTED:'In progress',
      CODING_CHALLENGE_COMPLETED:'Onhold',
      CODING_CHALLENGE_REJECTED:'Rejected',

      CODING_CHALLENGE_CLEARED:'Discussion in progress',
      WHITEBOARD_READY:'Discussion in progress',
      WHITEBOARD_INITIATED:'Onhold',
      WHITEBOARD_REJECTED:'Rejected',

      WHITEBOARD_CLEARED:'In progress',
      LEADERSHIP_CONNECT_READY:'In progress',
      LEADERSHIP_CONNECT_REJECTED:'Rejected',
      LEADERSHIP_CONNECT_CLEARED:'Selected',
    }

    imageUrl = environment.imageUrl;
  constructor(protected localStorageService: LocalStorageService,
              private AuthService: AuthService,
              private router: Router,
              private route: ActivatedRoute,
              private toastr: ToastsManager,
              private navBarService: NavBarService,
              private pagerService: PagerService,
              private modalService: TaModalServiceService,
              private WorkspaceService:WorkspaceService,) {
    //this.navBarService.setCurrentPage(0);
    this.allClass = 'rgb(0,204,255)';
    this.allClassColor = 'rgb(255, 255, 255)';
    this.pendingClass = "rgb(255, 255, 255)";
    this.inProgressClass = "rgb(255, 255, 255)";

    this.userIcon = '';
    this.isApprove = false
    this.selectUser = true
    this.name = ''
    this.fullName = ''
    var empData
    empData = this.localStorageService.get('userInfo');
    this.empData = empData;
    this.navBarService.setCurrentPage(8);

    this.route.queryParams.subscribe(val => {
      console.log(val, 'val of paramssss');
      if (val.param == 'reload') {
        this.router.navigate(['/ta']);
      }
    })


    console.log('back nav bt --- ', this.backNavClicked);
    this.name = this.empData['firstName'];
    this.fullName = this.empData['fullName'];

    this.reqJson['userInfoMstrId'] = this.empData.userInfoMstrId

    this.subscriptions.push(this.modalService.modal_content.subscribe(content => this.modalContent = content));
    this.subscriptions.push(this.modalService.candidate.subscribe(candidate => this.modalCandidate = candidate));


    console.log(this.levels);

    console.log(new Date());

    var Today = new Date();
    console.log(Today,'todayyyyyyyyyyyyy');
    var day = Today.getDate();
    var monthIndex = Today.getMonth();
    var currentmonthIndex = monthIndex+1;
    var year = Today.getFullYear();

    this.model= { endDate: {year: year, month: currentmonthIndex, day: day},
      beginDate: {year: year, month: monthIndex, day: day}}

    this.myDateRangePickerOptions = {
      disableSince :{year: year, month: currentmonthIndex, day: day+1}

    }


    this.AuthService.getLocations().then(res => {
      const skill = res;
      this.locations = skill.pgLocationList;
      console.log(this.locations, 'locations');
    }).catch(err => {
      console.log(err);
    });

    this.AuthService.getAllExperienceLevel().then(res => {
      const exp = res;
      this.expLevels = exp.pgExperienceList;
      console.log(this.expLevels, 'getAllExperience');
    }).catch(err => {
      console.log(err);
    });

    this.AuthService.getAllAssessment().then(res => {
      const assess = res;
      this.jobAssessments = assess;
      console.log(this.jobAssessments, 'assess');
    }).catch(err => {
      console.log(err);
    });

     this.filterItem = this.localStorageService.get('FilterItem')

      if(this.filterItem) {
        this.levelFilters = this.filterItem.level || [];
         this.locationFilters = this.filterItem.location || [];
         this.jobFilters = this.filterItem.jobId || [];
         //this.jobFilters = this.filterItem.statusActive;

        this.reqJson.experienceLevel = this.filterItem.level || [];
        this.reqJson.locations = this.filterItem.location || [];
        this.reqJson.jobName = this.filterItem.jobId || [];

        if(this.getRole() === 'COACH'){
          if(this.filterItem.statusActive == 'S3'){
            this.step3();
          } else {
            this.step4();
          }

        } else {
          if(this.filterItem.statusActive == 'S1'){
            this.step1();
          } else if(this.filterItem.statusActive == 'S2'){
            this.step2();
          } else if(this.filterItem.statusActive == 'S3'){
            this.step3();
          } else if(this.filterItem.statusActive == 'S4'){
            this.step4();
          } else if(this.filterItem.statusActive == 'S5'){
            this.step5();
          } else {

          }
        }

      } else {
        if(this.getRole() === 'COACH'){
          this.step3();

        } else {
          this.step1();
        }

      }
    console.log(this.filterItem,'filterItem');




  }



  getDateFormat(e){

    console.log(e);
    console.log(this.model);

    if(e.beginJsDate && e.endJsDate){

      this.reqJson.fromDate = e.beginDate.year+'-'+e.beginDate.month+'-'+e.beginDate.day;
      this.reqJson.toDate = e.endDate.year+'-'+e.endDate.month+'-'+e.endDate.day
      if(this.filterActive == "S1"){
        this.step1();

      }
      if(this.filterActive == "S2"){
        this.step2();

      }
      if(this.filterActive == "S3"){
        this.step3();

      }
      if(this.filterActive == "S4"){
        this.step4();

      }
      if(this.filterActive == "S5"){
        this.step5();
      }
    } else {
      this.reqJson.fromDate = null;
      this.reqJson.toDate = null;
      var Today = new Date();
      console.log(Today,'todayyyyyyyyyyyyy');
      var day = Today.getDate();
      var monthIndex = Today.getMonth();
      var currentmonthIndex = monthIndex+1;
      var year = Today.getFullYear();

      this.model= { endDate: {year: year, month: currentmonthIndex, day: day},
        beginDate: {year: year, month: monthIndex, day: day}}


      console.log(this.model);


      if(this.filterActive == "S1"){
        this.step1();

      }
      if(this.filterActive == "S2"){
        this.step2();

      }
      if(this.filterActive == "S3"){
        this.step3();

      }
      if(this.filterActive == "S4"){
        this.step4();

      }
      if(this.filterActive == "S5"){
        this.step5();
      }
    }


  }


  getcandidateList(state){
    console.log(this.reqJson, state);



    this.AuthService.getAllCandidateLists(this.reqJson,state).then(responseData => {

      console.log(responseData)
      this.rowCopy = responseData

      this.candidateList = this.rowCopy;
      this.candidateListCopy = this.candidateList;
      this.candidateListSearchCopy = this.candidateList;
      this.levels = _.uniqBy(this.rowCopy, 'expLevel')
      this.city = _.uniqBy(this.rowCopy, 'location')
      this.jobTitles = _.uniqBy(this.rowCopy, 'jobName')
      this.statusList = _.uniqBy(this.rowCopy, 'userStatus')

      /*CODING CHALLENGE CHECK*/
      if(this.filterActive == 'S3'){

        let checkSts = this.statusList.filter(usr=>{
          return  usr.userStatus =='CODING_CHALLENGE_READY';
        })

        if(checkSts.length !== 0){
          this.statusList = this.statusList.filter(user=>{

            return user.userStatus !== "METTL_CLEARED"
          })
        } else {
          this.statusList = this.statusList.filter(user=>{

            return user.userStatus !== "CODING_CHALLENGE_READY"
          })
        }


      }

      /*WHITEBOARD STATUS CHECK*/

      if(this.filterActive == 'S4'){

        let checkSts = this.statusList.filter(usr=>{
          return  usr.userStatus =='WHITEBOARD_READY';
        })

        if(checkSts.length !== 0){
          this.statusList = this.statusList.filter(user=>{

            return user.userStatus !== "CODING_CHALLENGE_CLEARED"
          })
        } else {
          this.statusList = this.statusList.filter(user=>{

            return user.userStatus !== "WHITEBOARD_READY"
          })
        }


      }
      /*LEADER SHIP STATUS CHECK*/

      if(this.filterActive == 'S5'){

        let checkSts = this.statusList.filter(usr=>{
          return  usr.userStatus =='LEADERSHIP_CONNECT_READY';
        })

        if(checkSts.length !== 0){
          this.statusList = this.statusList.filter(user=>{

            return user.userStatus !== "WHITEBOARD_CLEARED"
          })
        } else {
          this.statusList = this.statusList.filter(user=>{

            return user.userStatus !== "LEADERSHIP_CONNECT_READY"
          })
        }


      }

      this.onSelectedCandidate = [];
      this.empList = []
      this.footerShow = false;
      this.isLoader = true;
      if(this.candidateList.length !== 0) {
        this.setPage(1);
      }
    })

  }


  showLocationFilter(){
    this.locationArrow =  !this.locationArrow;
  }
  showLevelFilter(){
    this.levelArrow =  !this.levelArrow;
  }
  showjobFilter(){
    this.jobArrow =  !this.jobArrow;
  }
  showStatusFilter(){
    this.statusArrow =  !this.statusArrow;
  }

  resetFilter(){
    this.reqJson = {
      experienceLevel: null,
      fromDate:null,
      jobName: null,
      locations: null,
      skills:null,
      toDate:null,
      userInfoMstrId:null
    }
    this.locations = [];
    this.expLevels = [];
    this.jobAssessments = [];

    this.levelFilters = [];
    this.jobFilters = [];
    this.skillFilters = [];
    this.locationFilters = [];
    this.statusFilters = [];

    this.reqJson['userInfoMstrId'] = this.empData.userInfoMstrId
    this.AuthService.getLocations().then(res => {
      const skill = res;
      this.locations = skill.pgLocationList;
      console.log(this.locations, 'locations');
    }).catch(err => {
      console.log(err);
    });

    this.AuthService.getAllExperienceLevel().then(res => {
      const exp = res;
      this.expLevels = exp.pgExperienceList;
      console.log(this.expLevels, 'getAllExperience');
    }).catch(err => {
      console.log(err);
    });

    this.AuthService.getAllAssessment().then(res => {
      const assess = res;
      this.jobAssessments = assess;
      console.log(this.jobAssessments, 'assess');
    }).catch(err => {
      console.log(err);
    });

    this.checkTap()
  }





  ngOnInit() {
    // this.navBarService.setCurrentPage(10);
    console.log('back nav bt --- ',this.backNavClicked);
    this.currentPageData = { title: 'List of Profiles', back: 'menu' };
  }


  /* Search function */

  insearch(searchword) {
    const kw = searchword.value;
    console.log(kw.length);
    if (kw.length > 0 ) {
      this.candidateList = this.candidateListSearchCopy.filter(x => {
        //  console.log(x.jobName);
        // console.log(x.jobName.toNumber());

        if(x.jobName &&  x.expLevel) {
          return x.fullName.toLowerCase().includes(kw.toLowerCase())
            || x.email.toLowerCase().includes(kw.toLowerCase()) || x.expLevel.toLowerCase().includes(kw.toLowerCase())
            || x.jobName.toLowerCase().includes(kw.toLowerCase())
        }else {
          return x.fullName.toLowerCase().includes(kw.toLowerCase()) || x.email.toLowerCase().includes(kw.toLowerCase())
        }

      });
      this.candidateListCopy = this.candidateList;
      if(this.candidateList.length !== 0) {
        this.setPage(1);
      }
    }
    else {
      this.candidateList = this.candidateListSearchCopy;
      this.setPage(1);

    }
  }



  ngOnDestroy() {
    this.subscriptions.forEach(sub => sub.unsubscribe());
  }



  /*ONBOARD CHALLENGE */
  step1() {
    this.filterActive = 'S1';
    this.isLoader = false;
    this.userFilter.fullName = null
    this.localStorageService.set('FilterItem',{level:this.levelFilters,location:this.locationFilters,jobId:this.jobFilters,statusActive:this.filterActive})

    this.getcandidateList('ONBOARDED')


  }
  /*METTL CHALLENGE */
  step2() {
    this.filterActive = 'S2';
    this.isLoader = false;
    this.localStorageService.set('FilterItem',{level:this.levelFilters,location:this.locationFilters,jobId:this.jobFilters,statusActive:this.filterActive})

    this.getcandidateList('PC')

  }
  /*CODING CHALLENGE */
  step3() {
    this.candidateList = [];
    this.filterActive = 'S3';
    this.isLoader = false;
    this.localStorageService.set('FilterItem',{level:this.levelFilters,location:this.locationFilters,jobId:this.jobFilters,statusActive:this.filterActive})

    this.getcandidateList('CC')

  }


  /*WHITEBOARD CHALLENGE*/
  step4() {
    this.filterActive = 'S4';
    this.isLoader = false;
    this.localStorageService.set('FilterItem',{level:this.levelFilters,location:this.locationFilters,jobId:this.jobFilters,statusActive:this.filterActive})

    this.getcandidateList('WC')
  }
  /*LEADERSHIP CHALLENGE*/
  step5() {
    this.filterActive = 'S5';
    this.isLoader = false;
    this.localStorageService.set('FilterItem',{level:this.levelFilters,location:this.locationFilters,jobId:this.jobFilters,statusActive:this.filterActive})

    this.getcandidateList('LC')
  }


  private updateSidebarFilters() {
    this.skills = _.uniq(_.flattenDeep(this.candidatesList.map(i => i.skillTrackDtlsName)));
    this.jobTitles = _.uniqBy(this.candidatesList, 'jobName');
    this.levels = _.sortBy(this.levels, _.uniqBy(this.candidatesList, 'experienceLevel'), 'experienceLevelId');
    this.city = _.uniqBy(this.candidatesList, 'city');
    this.resetFilters();
  }

  checkTap(){
    if(this.filterActive == "S1"){
      this.step1();

    }
    if(this.filterActive == "S2"){
      this.step2();

    }
    if(this.filterActive == "S3"){
      this.step3();

    }
    if(this.filterActive == "S4"){
      this.step4();

    }
    if(this.filterActive == "S5"){
      this.step5();
    }
  }

  searchCity(id) {
    this.toggleFilter(id, this.locationFilters);
    this.reqJson.locations = this.locationFilters;
    if(this.filterActive == "S1"){
      this.step1();

    }
    if(this.filterActive == "S2"){
      this.step2();

    }
    if(this.filterActive == "S3"){
      this.step3();

    }
    if(this.filterActive == "S4"){
      this.step4();

    }
    if(this.filterActive == "S5"){

    }
    this.localStorageService.set('FilterItem',{level:this.levelFilters,location:this.locationFilters,jobId:this.jobFilters,statusActive:this.filterActive})


  }

  skillFilter(skill) {
    this.toggleFilter(skill, this.skillFilters);
    this.reqJson.skills = this.skillFilters;
    if(this.filterActive == "S1"){
      this.step1();

    }
    if(this.filterActive == "S2"){
      this.step2();

    }
    if(this.filterActive == "S3"){
      this.step3();

    }
    if(this.filterActive == "S4"){
      this.step4();

    }
    if(this.filterActive == "S5"){

    }
  }

  levelFilter(level) {
    this.toggleFilter(level, this.levelFilters);
    console.log(this.levelFilters);
    if(this.levelFilters.length == 0){
      this.levelFilters = [];
    } else {
      this.reqJson.experienceLevel = this.levelFilters;
    }
    if(this.filterActive == "S1"){
      this.step1();

    }
    if(this.filterActive == "S2"){
      this.step2();

    }
    if(this.filterActive == "S3"){
      this.step3();

    }
    if(this.filterActive == "S4"){
      this.step4();

    }
    if(this.filterActive == "S5"){

    }
    this.localStorageService.set('FilterItem',{level:this.levelFilters,location:this.locationFilters,jobId:this.jobFilters,statusActive:this.filterActive})
  }

  jobTitleFilter(title) {
    this.toggleFilter(title, this.jobFilters);
    this.reqJson.jobName = this.jobFilters;
    if(this.filterActive == "S1"){
      this.step1();

    }
    if(this.filterActive == "S2"){
      this.step2();

    }
    if(this.filterActive == "S3"){
      this.step3();

    }
    if(this.filterActive == "S4"){
      this.step4();

    }
    if(this.filterActive == "S5"){
      this.step5();
    }
    this.localStorageService.set('FilterItem',{level:this.levelFilters,location:this.locationFilters,jobId:this.jobFilters,statusActive:this.filterActive})

  }

  stsFilter(title) {



    if(title === 'METTL_CLEARED'){
      this.toggleFilter(title, this.statusFilters);
      this.toggleFilter('CODING_CHALLENGE_READY', this.statusFilters);

    } else if(title === 'CODING_CHALLENGE_CLEARED'){
      this.toggleFilter(title, this.statusFilters);
      this.toggleFilter('WHITEBOARD_READY', this.statusFilters);

    } else if(title === 'WHITEBOARD_CLEARED'){
      this.toggleFilter(title, this.statusFilters);
      this.toggleFilter('LEADERSHIP_CONNECT_READY', this.statusFilters);

    } else {
      this.toggleFilter(title, this.statusFilters);

    }
   console.log(this.statusFilters)
  // console.log(title)

    let filter = this.statusFilters
    if(filter.length !== 0) {
      this.candidateList = this.candidateListSearchCopy.filter(function (item, index, array) {
        return filter.includes(item.userStatus);
      })
      setTimeout(() => {
        this.candidateListCopy = this.candidateList;
        this.setPage(1);
      }, 500);
    }
    else {
      this.checkTap();
    }
  }


  statusFilter(evnt,sts){
    console.log(sts);
    this.candidateList = this.candidateListSearchCopy.filter(x => {
      return x.userStatus == sts
    })

    setTimeout(() => {
      this.candidateListCopy = this.candidateList;
      this.setPage(1);
    }, 500);



    //  this.setPage(1);
  }

  private toggleFilter(filter: string, filterArray: string[]) {
    if (filterArray.includes(filter)) {
      let index = filterArray.indexOf(filter);
      filterArray.splice(index, 1);
    } else {
      filterArray.push(filter);
    }
  }
  resetFilters() {
    this.levelFilters = [];
    this.jobFilters = [];
    this.skillFilters = [];
    this.locationFilters = [];
  }


  mouseleft(index) {
    this.isRow = 0.5
  }
  over(index) {
    this.isRow = index
  }

  callMe() {
    this.userIcon = 'logout';
    console.log('callme');

  }

  leaveLogout(eventObject) {

    this.userIcon = '';

  }

  logout() {
    console.log("logout");
    this.localStorageService.clearAll();
    localStorage.clear();
    this.router.navigate(['']);

  }
  goToDashboard() {
    this.router.navigate(['/ta']);
  }

  filterEnb(){
    this.filterBtn = !this.filterBtn;
  }
  redirectReport (){
    this.router.navigate( ['ta/reports'])
  }

  scheduleTest(id) {
    this.router.navigate(['/ta', 'taProfile', id]);
  }

  /*candidateStatusCheck(userId, status) {
    console.log(userId, status)

    this.AuthService.candidateStatusUpdate({ candidateStatus: status, fromId: this.empData.userInfoMstrId, toId: userId }).then(responseData => {
      console.log(responseData)
      var responseDataCheck = responseData
      // var resData = responseData['data']

      if (responseData['status'] == 'success') {

        if (status == 'TA_APPROVED') {
          this.toastr.success("Candidate approved for the Playground");
          this.router.navigateByUrl('/taProfile?uuid=' + userId);
        }
        else if (status == 'TA_REJECTED') {
          this.toastr.success("Candidate rejected from the PlayGround");
          for (var key in this.listCandidates) {
            if (this.listCandidates[key].userInfoMstrId == userId) {
              this.listCandidates[key].status = 'TA_REJECTED';
            }
          }
        }

      }
      else {
        console.log(responseData, 'Else case Canditates Approval ')
      }
      console.log(this.candidatesList);
    }).catch(err => {
      console.log(err)
    });
  }*/

  cardClick($event, id, status) {
    if ($event.target.getAttribute('data-toggle')) {
      return;
    }
    this.router.navigate(['/ta', 'taProfile', id]);
  }

  skillMstrs(userData) {
    this.masterSkillId = []
    this.masterSkills = []
    this.masterSkills = _.uniqBy(userData.userInfoMstr.pgUserSkillMapping, 'pgSkillTrackDtls.pgSkillTrackMstr.description');


    this.masterSkills.forEach(usrSkills => {
      this.masterSkillId.push(usrSkills.pgSkillTrackDtls.pgSkillTrackMstr.description);
    });
    return this.masterSkillId;
  }


  onUnovering(eventObject, index) {

    this.isRow = null;

  }


  Initials(cString) {

    if (cString) {
      return cString.replace(/\W*(\w)\w*/g, '$1').toUpperCase()
    }
  }

  clear(){
    this.footerShow = !this.footerShow;
    this.checkTap();

  }


  footerSubmitPC(status) {
    if (this.onSelectedCandidate.length !== 0) {

      var reqJson = {
        userIds: this.onSelectedCandidate,
        status: status,
        loggedInUser: this.empData.email,
        eventId: 1
      }

      this.updateStatusPC(reqJson)

    }
  }

  footerSubmit() {
    console.log("clicked");

    if(this.onSelectedCandidate.length !== 0) {

      let reqJson = {
        "candidateIds": this.onSelectedCandidate,
        "loggedInUser": this.empData.email
      }
      //e.stopPropagation();
      /* this.modalService.selectCandidate(e.userId);
       this.modalService.showModal(e.status);*/
      this.AuthService.getInvite(reqJson).then(responseData => {

        console.log(responseData)
        this.checkTap();

        this.toastr.success(responseData.message)


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

  }

  onCheckCandidate(e){
    console.log(e);
    if(e.userIds.length !== 0){
      this.footerShow = true
      this.onSelectedCandidate = e.userIds;
      this.empList = e.userDetails;
      console.log(this.onSelectedCandidate);

    } else {
      this.footerShow = false
    }
  }

  selectCandidate(e) {
    let reqJson = {"candidateIds" : [e.userId],
      "loggedInUser" : this.empData.email}
    //e.stopPropagation();
    /* this.modalService.selectCandidate(e.userId);
     this.modalService.showModal(e.status);*/
    this.AuthService.getInvite(reqJson).then(responseData => {

      this.checkTap();

      this.toastr.success(responseData.message)


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



  updateStatusPC(data){
    this.AuthService.getUpdateCandidateStatus(data).then(responseData => {

      if(responseData.status == 'success') {
        this.checkTap();

        this.toastr.success(responseData.message)
      } else {
        this.toastr.error(responseData.message)

      }

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

  }



  BUPage(){
    // this.navBarService.setCurrentPage(9);
    console.log('BulkUpload clicked');
  }

  setPage(page: number) {
    console.log(this.pager);
    if(this.pager.totalPages){
      if (page < 1 || page > this.pager.totalPages) {
        return;
      }
    }
    // get pager object from service
    this.pager = this.pagerService.getPager(this.candidateListCopy.length, page);
    console.log("Pager --- "+JSON.stringify(this.pager));
    // get current page of items
    this.candidateList = this.candidateListCopy.slice(this.pager.startIndex, this.pager.endIndex + 1);
    this.rowIndex = 1;
    this.showFNm = false;
  }
  onSelectCoach(e) {
    console.log(e);
    this.empList = e.user
    this.selectModalValue = e.event;
    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 => {

        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;

        }

        //  this.assessments = resp.businessUseCase.useCaseList.concat(resp.technicalUseCase.useCaseList);
        console.log(this.assessments);
        console.log(this.empList);
        document.getElementById('openModalButton').click();

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


  }

  footerSubmitCC(e){
    if(e === 'initiate'){

      var reqJson ={
        userIds: this.onSelectedCandidate,
        status: 'CODING_CHALLENGE_INITIATED',
        loggedInUser: this.empData.email,
        eventId: 2
      }
      console.log(reqJson);
      this.updateStatusPC(reqJson)
    } else {
      this.onMultiSelectCoach(e);
    }
  }

  onMultiSelectCoach(e) {
    console.log(e);
    // this.empList = e.user
    this.selectModalValue = e;
    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 => {

        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;

        }

        //  this.assessments = resp.businessUseCase.useCaseList.concat(resp.technicalUseCase.useCaseList);
        console.log(this.assessments);
        console.log(this.empList);
        document.getElementById('openModalButton').click();

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


  }

  footerSubmitWC(e){

    var reqJson = {
      userIds: this.onSelectedCandidate,
      status: e,
      loggedInUser: this.empData.email,
      eventId: 3
    }
    console.log(reqJson);
    this.updateStatusPC(reqJson)

  }
  footerSubmitLC(e){

    var reqJson = {
      userIds: this.onSelectedCandidate,
      status: e,
      loggedInUser: this.empData.email,
      eventId: 4
    }
    console.log(reqJson);
    this.updateStatusPC(reqJson)

  }



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

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

  }
  selectedAssess(data){
    console.log(data);
    this.assessmentSelected = data;
    this.onSelectedCandidate = [];
    this.empList.forEach(usr => {
      this.onSelectedCandidate.push(usr.userInfoMstrId)
    })

  }
  submitCoachUpdate(){
    var reqJson = {
      "id": this.coachSelected,
      "loggedInUser": this.empData.email,
      "userInfoMstrIds": this.onSelectedCandidate,
    }

    var path = 'CC';

    if(this.filterActive === "S3"){
      path = 'CC'

    }else if(this.filterActive === "S4"){
      path = 'WC'
    }
    else if(this.filterActive === "S5"){
      path = 'LC'
    } else {

    }

    console.log(this.filterActive,path);
    this.AuthService.getUpdateCoach(reqJson,path).then(resp => {

      console.log(resp);
      if(resp.status === 'success'){
        this.toastr.success(resp.message)
        this.empList = []
        this.closeModal();
        this.checkTap()
      } else {
        this.toastr.error(resp.message)

      }


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

  submitAssessmentUpdate(){
    var reqJson = {
      "id": this.assessmentSelected,
      "loggedInUser": this.empData.email,
      "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.empList = []
        this.closeModal();
        this.checkTap()
      } else {
        this.toastr.error(resp.message)

      }

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





  codingChange(e){
    console.log(e);
    let reqJson ={
      userIds: e.userId,
      status: e.status,
      loggedInUser: this.empData.email,
      eventId: 2
    }
    console.log(reqJson);
    console.log('setupworkspaces');
    this.isLoader = !this.isLoader;
    this.AuthService.getUserInfoBy({adId:e.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)
            this.isLoader = !this.isLoader;

          }
          else {
            this.updateStatusPC(reqJson)
            this.isLoader = !this.isLoader;

          }
        }).catch(wsErr => {
          console.log(wsErr,'workSpace Error')
          this.isLoader = !this.isLoader;

        })
      }

      else {
        //console.log(this.respData)
        this.isLoader = !this.isLoader;
      }
    }).catch(getWorkspaceErr => {
      console.log(getWorkspaceErr,'getWorkspaceErr')
      this.isLoader = !this.isLoader;

    })

    //
  }


  primaryChange(evnt){
    console.log(evnt);
    var reqJson ={
      userIds: evnt.userId,
      status: evnt.status,
      loggedInUser: this.empData.email,
      eventId: 1
    }
    console.log(reqJson);

    document.getElementById('openModalButton').click();
    this.modalData = evnt.data;
    this.modalUserId =evnt.userId[0];
    this.modalModal = evnt.modal;
    this.modalStatus = evnt.status;
    console.log(this.filterActive);

    // this.modalAdId = e.adId;
    // this.updateStatusPC(reqJson)
  }


  whiteboardChange(e){
    console.log(e);
    var reqJson ={
      userIds: e.userId,
      status: e.status,
      loggedInUser: this.empData.email,
      eventId: 3
    }
    console.log(reqJson);

    if(e.status === 'WHITEBOARD_REJsECTED'){
      this.terminateWorkSpace({adId:e.adId})
    }
   // this.updateStatusPC(reqJson)
    document.getElementById('openModalButton').click();
    this.modalData = e.data;
    this.modalUserId =e.userId[0];
    this.modalModal = e.modal;
    this.modalStatus = e.status;
  }

  leaderboardChange(e){
    console.log(e);
    var reqJson ={
      userIds: e.userId,
      status: e.status,
      loggedInUser: this.empData.email,
      eventId: 4
    }
    console.log(reqJson);
    //this.updateStatusPC(reqJson)
    this.terminateWorkSpace({adId:this.modalAdId})
    document.getElementById('openModalButton').click();
    this.modalData = e.data;
    this.modalUserId =e.userId[0];
    this.modalModal = e.modal;
    this.modalStatus = e.status;

  }

  onfeedBackCC(e){
    console.log(e);
    this.FBmodal = e.modal;
    document.getElementById('openModalButton').click();
    this.modalData = e.data;
    this.modalUserId =e.userId;
    this.modalModal = e.modal;
    this.modalStatus = e.status;
    this.modalAdId = e.adId;
  }

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

    if(this.filterActive === 'S2'){
      reqJson.level = 'PC';
    } else if(this.filterActive === 'S3'){
      reqJson.level = 'CC';
    } else if(this.filterActive === 'S4'){
      reqJson.level = 'WC';
    } else if(this.filterActive === 'S5'){
      reqJson.level = 'LC';
    } else {
      reqJson.level = '';
    }


    console.log(reqJson);
    console.log(this.modalStatus);
    console.log(this.modalAdId);

    if(this.modalStatus === 'CODING_CHALLENGE_REJECTED'){
      this.terminateWorkSpace({adId:this.modalAdId})
    }
    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();
        var reqJson ={
          userIds: [data.userId],
          status: this.modalStatus,
          loggedInUser: this.empData.email,
          headCoachComment: data.reviewFeedback,
          eventId: 2
        }

        if(this.filterActive === 'S2'){
          reqJson.eventId = 1
        } else if(this.filterActive === 'S3'){
          reqJson.eventId = 2
        } else if(this.filterActive === 'S4'){
          reqJson.eventId = 3
        } else if(this.filterActive === 'S5'){
          reqJson.eventId = 4
        } else {
          reqJson.eventId = 1
        }

        console.log(this.modalStatus);
        console.log(reqJson);
        this.updateStatusPC(reqJson)
      } else {
        this.toastr.error('Failed to save the details')

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


  terminateWS(e){
    this.AuthService.getWorkspaceId({adId:e.adId}).then(response => {

      console.log(response,'getworkSpace Details')

      let workSpaceData = JSON.parse(response['data']);
      console.log(workSpaceData, 'workSpaceData');
      let WorkspaceId = workSpaceData.workSpaceId;
      console.log(WorkspaceId, 'WorkspaceId');
      this.WorkspaceService.terminateWorkspaces({Id: WorkspaceId,sname:e.adId}).then(resp => {
        console.log(resp, 'terminateWorkspaces');

        if(resp) {

          this.AuthService.updateAwsWorkspaceStatus(e.adId, 'Terminated');
          this.toastr.success('Workspace terminated successfully')
        }
        else {
          this.toastr.error('something went wrong')
          console.log("workspace couldnot be terminated");
        }
      }).catch(err => {
        console.log(err);
      });

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

  }

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

  showCanDetPage(e){
    this.canDetailToShow = e;
    console.log('clicked passed data === ', e);
    console.log('clicked passed data === ', JSON.stringify(this.canDetailToShow));
    //this.candDetailPgNew = true;
    this.router.navigate(['ta/taProfile/'+e.candidateDetails.userInfoMstrId]);
  }

  getRole(){
    return this.localStorageService.get('userSession');

  }

  terminateWorkSpace(e){

    this.AuthService.getWorkspaceId({adId:e.adId}).then(response => {

      console.log(response,'getworkSpace Details')

      let workSpaceData = JSON.parse(response['data']);
      console.log(workSpaceData, 'workSpaceData');
      let WorkspaceId = workSpaceData.workSpaceId;
      console.log(WorkspaceId, 'WorkspaceId');
      this.WorkspaceService.terminateWorkspaces({Id: WorkspaceId,sname:e.adId}).then(resp => {
        console.log(resp, 'terminateWorkspaces');

        if(resp) {

          this.AuthService.updateAwsWorkspaceStatus(e.adId, 'Terminated')
        }
        else {
          console.log("workspace couldnot be terminated");
        }
      }).catch(err => {
        console.log(err);
      });

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

  }

}

