import { Component, HostListener,Input,OnInit} from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';
import {Router, ActivatedRoute} from '@angular/router';
import {NavigationService} from '../../services/navigation/navigation.service'
import {WorkspaceService} from '../../services/workspace.service';
import {DomSanitizer,SafeResourceUrl,} from '@angular/platform-browser';
import {el} from "@angular/platform-browser/testing/src/browser_util";
import {URLSearchParams} from "@angular/http";
import {MatProgressSpinnerModule, MatSliderModule} from '@angular/material';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import {forEach} from "@angular/router/src/utils/collection";
import _ from "lodash";
//import { NavBarService } from '../coach.service';
import {SchedulePrimaryTestDataService} from './../../coach/shared/service/schedule-primary-test-data.service';

import { Utils } from 'app/utils';
import { InfoDetails } from 'app/models/candidate-dashboard-response/info-details';
import { CandidateDashboardResponse } from 'app/models/candidate-dashboard-response/candidate-dashboard-response';
import {CoachCandidateEvaluationService} from 'app/coach/shared/service/coach-candidate-evaluation.service';
import { Assessment } from 'app/models/assessment/assessment.model';
import { environment } from '../../../environments/environment.dev';

@Component({
  selector: 'app-candidate-event-details',
  templateUrl: './candidate-event-details.component.html',
  styleUrls: ['./candidate-event-details.component.scss']
})
export class CandidateEventDetailsComponent implements OnInit {


  @Input() coreComment: string='';
  @Input() digitalComment: string='';
  @Input() overAllComment: string='';
  @Input() bsncoreComment: string='';
  @Input() bsndigitalComment: string='';
  @Input() bsnoverAllComment: string='';

// TODO: need to find out what is the right role
  role: String = "PGM";

  candidateDashboard: CandidateDashboardResponse;
  assessment: Assessment = new Assessment();
  candt:{ };
  CandidateData=false;
  UserID :string;
  userIcon='';
  userId='';
  iFrm=false;
  public fulName:string;
  scorecard=[0,1,2,3,4,5,6,7,8,9,10];
  totalScore=0;

  description = [];
  eveDlts = [];
  eveDltsDesc = [];
  eventCapabilitiesList =[];
  capabilitesIndex=[];

  PG='';
  modal='';
  ADID = '';
  workspcId:{}
  workSpaceData:{
    registrationCode:string,
    adId:string,
    workSpaceId:string,
    awsClientAccessUrl:string,
    errorBean:string,
    computerName:string

  }
  workspaceId:any;
  computerName:any;
  respData: any;

  describeSuccess:boolean;
  workSpaceSuccess:boolean;
  reqData:any;
  coreScore=0;
  digiScore=0;
  corebsnsScore=0;
  digibsnsScore=0;


  point1=-1;
  point2=-1;
  point3=-1;
  point4=-1;
  point5=-1;
  digitechpoint1=-1;
  digitechpoint2=-1;
  digitechpoint3=-1;
  digitechpoint4=-1;
  digitechpoint5=-1;
  pointbsns1=-1;
  pointbsns2=-1;
  pointbsns3=-1;
  pointbsns4=-1;
  pointbsns5=-1;
  digitechpointbsns1=-1;
  digitechpointbsns2=-1;
  digitechpointbsns3=-1;
  digitechpointbsns4=-1;
  digitechpointbsns5=-1;

  cmtEnable = false

  mindscore= 0;
  adaptiveScore = 0;
  fullstackScore= 0;
  transdisScore=0;
  ccScore=0;

  mangAmbScore=0;
  culturalScore=0;
  learningScore=0;
  creativeInnovScore=0;
  organisationValScore=0;

  bsnsmindscore= 0;
  bsnsadaptiveScore = 0;
  bsnsfullstackScore= 0;
  bsnstransdisScore=0;
  bsnsccScore=0;

  bsnsmangAmbScore=0;
  bsnsculturalScore=0;
  bsnslearningScore=0;
  bsnscreativeInnovScore=0;
  bsnsorganisationValScore=0;

  statusMsg = '';
  techEval= 'Core';
  bsnsEval = 'Core';
  mettleReport:SafeResourceUrl;

  fName='';
  techEnable:string
  bussEnable:string
  evaluatingskill='Evaluation Report';


  userData:{
    userInfoDtlsId: string,
    adId: string,
    fullName:string,
    email:string,
    location:string,
    userInfoMstr :{
      firstNm:string,
      fullName:string,
      email:string,
      status: any,
      userInfoMstrId: string,
      pgUserSkillMapping:[{
        pgSkillTrackDtls:{
          pgSkillTrackMstr:{
            description:string,
            skillTrackName:string
          },
          description:string,
        },
      }]
    },
    experienceLevel:string,
    emailId:string,
    jobId:string,
    alternativeEmail:string,
    contactNumber:string,
    alternativeContact:string,
    governmentId:string,
  }
  name:string;

  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any
  };
  fullName:string;
  //launchUrl='https://pgfiles.altimetrik.com/files#/';

  launchUrl='';
  scoreColor = 'primary';
  Viewtechusecase=false;
  Viewbsnsusecase=false;
  showawspopover:boolean;
  techusecaseINFO:any;
  bsnsusecaseINFO:any;

  masterSkills:any;
  masterSkillIds= [];
  Schedules:any[];
  evaluationCriteria=[];

  schedulePrimaryTest:any;
  coachEvaluation : {description: any[],event:'',overAllComment:''};

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

  constructor(protected localStorageService: LocalStorageService,
              private AuthService:AuthService,
              private router: Router,
              private activeRoute:ActivatedRoute,
              private navigate:NavigationService,
              private route:ActivatedRoute,
             // private navBarService: NavBarService,
              private WorkspaceService:WorkspaceService,
              private sanitizer:DomSanitizer,
              private toastr: ToastsManager,
              private primaryTestService:SchedulePrimaryTestDataService,
              private coachCandidateEvaluationService:CoachCandidateEvaluationService) {

    //this.navBarService.setCurrentPage(1);

    var url_string = window.location.href;
    var url = new URL(url_string);




    this.route.params.subscribe( params =>
      this.UserID = params['id']
    );

    var empData
    empData = this.localStorageService.get('userInfo');
    this.empData = empData;
    console.log(this.empData,"userInfo Detailssssss")
    if(window.location.origin == 'http://localhost:8080'){
      this.name = 'UDAYANI'
      this.empData = {
        accessToken: '',
        loginType: '',
        fullName: 'Sabash LS',
        firstName: 'sabash',
        userInfoMstrId: 9,
        roleName: 'HEAD_COACH',
        roles: [1],
        skills: [1,2],
        location: 1
      };


    }
    else {
      if (this.empData['firstName']) {
        this.name = this.empData['firstName'];
        this.fullName = this.empData['fullName'];
      }
      else {
        this.name = ''
      }
    }

    if(!this.UserID) {
      this.router.navigate(['CFlanding']);
    }
    else {
      this.getCoachCandidate(this.UserID);
    }

    this.evaluationCriteria=[
      {
        "parameter":"core",
        "score":"80"
      },
      {
        "parameter":"digital",
        "score":"56"
      }
    ]
  }


  ngOnInit() {


  }

  getAdId(id){
    var email = id;
    var lasta = email.lastIndexOf('@');
    var name, host;
    if (lasta != -1) {

      return( email.substring(0, lasta));


    } else {
      /* respond to invalid email in some way */
    }
  }

  gocfLanding(){
    this.router.navigate(['coach/landing']);
  }

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


  getFirstName(fString){
    return fString.split(' ').slice(0, -1).join(' ');
  }

  editEvaluation($event){
    console.log($event);
  }

  autoTicks = false;
  disabled = false;
  invert = false;
  max = 100;
  min = 0;
  showTicks = false;
  step = 1;
  thumbLabel = false;
  value = 0;
  vertical = false;

  get tickInterval(): number | 'auto' {
    return this.showTicks ? (this.autoTicks ? 'auto' : this._tickInterval) : 0;
  }
  set tickInterval(v) {
    this._tickInterval = Number(v);
  }
  private _tickInterval = 1;

  getCoachCandidate(Id){

    this.AuthService.getCandidate({userInfoMstrId:Id}).then( responseData => {

      console.log(responseData);

      this.candt = responseData;
      this.candidateDashboard = responseData;
      this.assessment.setCandidateAssessment(responseData);
      this.eveDlts = responseData.eventDetails;
      this.eveDltsDesc = responseData.eventDetailsDesc;


      console.log(this.eveDltsDesc,"candidate::::::::::::::::::::::::::::::::::::::::::::::::::::::::",this.eveDlts[2].eventComments);

      this.userData = responseData.infoDetails;
      this.getMettleReport(this.userData.emailId);
      console.log(responseData.infoDetails.emailId, 'this.candt');

      if(this.userData.userInfoMstr.status == 'METTL_REVIEW'){
        this.techEnable = 'none';
        this.bussEnable = 'none';
      } else if(this.userData.userInfoMstr.status == 'METTL_APPROVED'){
        this.evaluatingskill= 'Technical Usecase Evaluation';
        this.techEnable = 'unset';
        this.bussEnable = 'none';

      }
      else if(this.userData.userInfoMstr.status == 'COACH_ASSIGNED' || this.userData.userInfoMstr.status == 'MINI_PG_COMPLETED' || this.userData.userInfoMstr.status == 'MINI_PG_STARTED' || this.userData.userInfoMstr.status == 'MINI_PG_COACH_APPROVED' || this.userData.userInfoMstr.status == 'MINI_PG_COACH_REJECTED'){
        this.evaluatingskill= 'Technical Usecase Evaluation';
        this.techEnable = 'unset';
        this.bussEnable = 'none';
        if(this.userData.userInfoMstr.status == 'MINI_PG_COACH_APPROVED' || this.userData.userInfoMstr.status == 'MINI_PG_COACH_REJECT'){
          this.techEval='';
        }
        if(this.userData.userInfoMstr.status == 'MINI_PG_COMPLETED'){
          this.ccIndex(2)
        }
        this.getusecase(this.UserID, 2);

      }
      else if(this.userData.userInfoMstr.status == 'MAIN_PG_COACH_ASSIGNED' || this.userData.userInfoMstr.status == 'MAIN_PG_COMPLETED' || this.userData.userInfoMstr.status == 'MAIN_PG_STARTED' || this.userData.userInfoMstr.status == 'MAIN_PG_COACH_REVIEWED' || this.userData.userInfoMstr.status == 'MAIN_PG_MANAGER_REJECTED' || this.userData.userInfoMstr.status == 'MAIN_PG_MANAGER_APPROVED' ) {
        this.evaluatingskill= 'Business Usecase Evaluation';
        this.techEnable = 'unset';
        this.bussEnable = 'unset';
        if(this.userData.userInfoMstr.status == 'MAIN_PG_COACH_REVIEWED' || this.userData.userInfoMstr.status == 'MAIN_PG_MANAGER_REJECTED'  || this.userData.userInfoMstr.status == 'MAIN_PG_MANAGER_APPROVED'){
          console.log(this.userData.userInfoMstr.status,'userStatus')
          this.assignBusinessUsecaseScore_Comments();

        }
        if(this.userData.userInfoMstr.status == 'MAIN_PG_COMPLETED'){
          this.ccIndex(3)
        }
        this.getusecase(this.UserID, 2);
        this.getusecase(this.UserID, 3);
      }


      console.log("candidate::",this.userData);

      this.fulName = responseData.infoDetails.userInfoMstr.fullName;

      this.ADID = responseData.infoDetails.adId;

      this.workspcId= {
        "adId":this.ADID
      };

      //assessment id information

      this.masterSkills =  _.uniqBy(this.userData.userInfoMstr.pgUserSkillMapping, 'pgSkillTrackDtls.pgSkillTrackMstr.description');


      this.masterSkills.forEach(usrSkills => {
        this.masterSkillIds.push(usrSkills.pgSkillTrackDtls.pgSkillTrackMstr.skillTrackMstrId);
      });

      this.AuthService.getAssessmentDetails(this.masterSkillIds).then(res => {
        this.respData = JSON.parse(res);

        this.masterSkillIds=[];
        this.masterSkills =  _.uniqBy(this.userData.userInfoMstr.pgUserSkillMapping, 'pgSkillTrackDtls.pgSkillTrackMstr.description');
        this.masterSkills.forEach(usrSkills => {
          this.masterSkillIds.push(usrSkills.pgSkillTrackDtls.description);
        });

        this.schedulePrimaryTest = [
          {
            candidateInfo:this.userData,
            assessmentIds:this.respData.pgAssessmentDtls,
            Skills:this.masterSkillIds,
            skillMaster: this.userData.userInfoMstr.pgUserSkillMapping[0].pgSkillTrackDtls.pgSkillTrackMstr.skillTrackName
          }
        ];

        console.log("this.schedulePrimaryTest",this.schedulePrimaryTest)
        this.primaryTestService.setPrimaryData(this.schedulePrimaryTest);
        this.CandidateData=true;

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

      //assessment id information


      console.log(this.candt);
      if(this.userData.userInfoMstr.status === 'COACH_ASSIGNED' ||
        this.userData.userInfoMstr.status == 'MINI_PG_STARTED' ||
        this.userData.userInfoMstr.status == 'MAIN_PG_STARTED' ||
        this.userData.userInfoMstr.status == 'MAIN_PG_COACH_ASSIGNED'){

        this.showawspopover = false;
      }
      else{
        this.showawspopover=  true;
      }


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

  }




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

  }
  getSubstring(text){
    if(text) {
      return text.substring(0, 3);
    }
  }
  showMettlReport(){
    this.evaluatingskill= 'Evaluation Report';
    this.iFrm = true;
  }

  getMettleReport(emailId){


    // var tempEmail = this.candt.infoDetails.emailId;
    this.AuthService.getCandidatePrimaryEvaluationReport({email:emailId}).then( responseData => {

      console.log(responseData);

      this.mettleReport = this.sanitizer.bypassSecurityTrustResourceUrl(responseData.candidate.testStatus.pdfReport);

      console.log(this.mettleReport);


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

  getTechnincalUsecaseResult(stats){

    if(stats == 'METTL_APPROVED' || stats == 'METTL_REJECTED' || stats == 'MINI_PG_STARTED' || stats == 'COACH_ASSIGNED'){
      console.log("MINI PG NOT COMPLETED");
    }
    else{
      if(stats == 'MINI_PG_COMPLETED') {

        this.ccIndex(2)
      }
      this.evaluatingskill= 'Technical Usecase Evaluation';
      this.iFrm = false;
    }

    if(this.eveDlts[1].eventOutput == 'MINI_PG_COACH_APPROVED'){

      this.assignTechnicalUsecaseScore_Comments()

      this.statusMsg = 'Approved'

    }

    else if(this.eveDlts[1].eventOutput == 'MINI_PG_COACH_REJECTED'){
      this.assignTechnicalUsecaseScore_Comments()
      this.statusMsg = 'Rejected'



    }

    else {


    }

  }

  getBusinessUsecaseResult(stats){

    this.description = []
    if(stats == 'METTL_APPROVED' || stats == 'METTL_REJECTED' || stats == 'MINI_PG_STARTED' || stats == 'COACH_ASSIGNED' || stats == 'MINI_PG_COMPLETED' || stats == 'MINI_PG_COACH_APPROVED' || stats == 'MINI_PG_COACH_REJECTED' || stats == 'MAIN_PG_COACH_ASSIGNED' || stats == 'MAIN_PG_STARTED'){
      console.log("MAIN PG NOT COMPLETED");
    }
    else{

      if(stats == 'MAIN_PG_COMPLETED') {

        this.ccIndex(3)
      }
      this.evaluatingskill= 'Business Usecase Evaluation';
      this.iFrm = false;

    }

    if(this.userData.userInfoMstr.status == 'MAIN_PG_COACH_REVIEWED'){
      this.assignBusinessUsecaseScore_Comments();
    }


  }

  finalCoreScore(score){

    this.coreScore = this.coreScore + score;
    console.log("coreScore"+this.coreScore);

  }


  getMindScore(score, rowcount){

    this.point1 = rowcount;
    console.log("mindscore"+this.mindscore);
    this.finalCoreScore(score-this.mindscore);
    this.mindscore = score;

  }



  getAdaptiveScore(score, rowcount){
    this.point2 = rowcount;
    console.log("getAdaptiveScore"+score);
    this.finalCoreScore(score-this.adaptiveScore);
    this.adaptiveScore = score;

  }




  getFullStackScore(score, rowcount){
    this.point3 = rowcount;
    console.log("fullstackScore"+score);
    this.finalCoreScore(score-this.fullstackScore);
    this.fullstackScore = score;
  }


  getTransdisScore(score, rowcount){
    this.point4 = rowcount;
    console.log("fullstackScore"+score);
    this.finalCoreScore(score-this.transdisScore);
    this.transdisScore = score;
  }


  getCCScore(score, rowcount){
    this.point5 = rowcount;
    console.log("fullstackScore"+score);
    this.finalCoreScore(score-this.ccScore);
    this.ccScore = score;
  }

  //tech-digi

  finalDigiScore(score){

    this.digiScore = this.digiScore + score;
    console.log("coreScore"+this.digiScore);
  }



  getManageAmbScore(score, rowcount){
    this.digitechpoint1 = rowcount;
    console.log("mangAmbScore"+score);
    this.finalDigiScore(score-this.mangAmbScore);
    this.mangAmbScore = score;
  }



  getCulturalScore(score, rowcount){
    this.digitechpoint2 = rowcount;
    console.log("mangAmbScore"+score);
    this.finalDigiScore(score-this.culturalScore);
    this.culturalScore = score;
  }



  getLearningScore(score, rowcount){
    this.digitechpoint3 = rowcount;
    console.log("learningScore"+score);
    this.finalDigiScore(score-this.learningScore);
    this.learningScore = score;
  }



  getCreativeInnovScore(score, rowcount){
    this.digitechpoint4 = rowcount;
    console.log("creativeInnovScore"+score);
    this.finalDigiScore(score-this.creativeInnovScore);
    this.creativeInnovScore = score;
  }


  getOrganisationValScore(score, rowcount){
    this.digitechpoint5 = rowcount;
    console.log("organisationValScore"+score);
    this.finalDigiScore(score-this.organisationValScore);
    this.organisationValScore = score;
  }

  //business score
  //core
  finalbsnsCoreScore(score){

    this.corebsnsScore = this.corebsnsScore + score;
    console.log("coreScore"+this.corebsnsScore);

  }



  getbsnsMindScore(score, rowcount){

    this.pointbsns1 = rowcount;
    console.log("mindscore"+this.bsnsmindscore);
    this.finalbsnsCoreScore(score-this.bsnsmindscore);
    this.bsnsmindscore = score;

  }



  getbsnsAdaptiveScore(score, rowcount){
    this.pointbsns2 = rowcount;
    console.log("getAdaptiveScore"+score);
    this.finalbsnsCoreScore(score-this.bsnsadaptiveScore);
    this.bsnsadaptiveScore = score;

  }




  getbsnsFullStackScore(score, rowcount){
    this.pointbsns3 = rowcount;
    console.log("fullstackScore"+score);
    this.finalbsnsCoreScore(score-this.bsnsfullstackScore);
    this.bsnsfullstackScore = score;
  }



  getbsnsTransdisScore(score, rowcount){
    this.pointbsns4 = rowcount;
    console.log("fullstackScore"+score);
    this.finalbsnsCoreScore(score-this.bsnstransdisScore);
    this.bsnstransdisScore = score;
  }

  getbsnsCCScore(score, rowcount){
    this.pointbsns5 = rowcount;
    console.log("fullstackScore"+score);
    this.finalbsnsCoreScore(score-this.bsnsccScore);
    this.bsnsccScore = score;
  }

  //digi bsns score

  finalbsnsDigiScore(score){

    this.digibsnsScore = this.digibsnsScore + score;
    console.log("coreScore"+this.digibsnsScore);
  }


  getbsnsManageAmbScore(score, rowcount){
    this.digitechpointbsns1 = rowcount;
    console.log("bsnsmangAmbScore"+score);
    this.finalbsnsDigiScore(score-this.bsnsmangAmbScore);
    this.bsnsmangAmbScore = score;
  }


  getbsnsCulturalScore(score, rowcount){
    this.digitechpointbsns2 = rowcount;
    console.log("bsnsmangAmbScore"+score);
    this.finalbsnsDigiScore(score-this.bsnsculturalScore);
    this.bsnsculturalScore = score;
  }


  getbsnsLearningScore(score, rowcount){
    this.digitechpointbsns3 = rowcount;
    console.log("bsnslearningScore"+score);
    this.finalbsnsDigiScore(score-this.bsnslearningScore);
    this.bsnslearningScore = score;
  }


  getbsnsCreativeInnovScore(score, rowcount){
    this.digitechpointbsns4 = rowcount;
    console.log("creativeInnovScore"+score);
    this.finalbsnsDigiScore(score-this.bsnscreativeInnovScore);
    this.bsnscreativeInnovScore = score;
  }


  getbsnsOrganisationValScore(score, rowcount){
    this.digitechpointbsns5 = rowcount;
    console.log("organisationValScore"+score);
    this.finalbsnsDigiScore(score-this.bsnsorganisationValScore);
    this.bsnsorganisationValScore = score;
  }


  /*10/05/2017*/

  showmodal( pg, val){


    //this.getWorkspaceInfo(adId);
    this.PG = pg;
    this.modal= val;
  }



  /*startWorkspace(workspaceId){
   console.log(workspaceId ,"startWorkspace")
   this.AuthService.startWorkspace({workSpaceId:workspaceId}).then(resp => {

   console.log("Startworkspace");
   console.log(resp, 'Startworkspace');
   if(resp.status){}
   }).catch(err =>{
   console.log(err)
   });
   }*/

  /*describeWorkspace(id){
   console.log(id,"describeWorkspace");
   this.AuthService.describeWorkspaceById({sdirId:id}).then(resp => {

   console.log("describeWorkspace");
   console.log(resp, 'describeWorkspace');
   this.describeSuccess = true;
   //this.computerName = resp;
   if(resp){
   this.computerName = resp;

   this.launchUrl = "https://pgfiles.altimetrik.com/files#/"+this.computerName+"/Users/"+this.ADID;
   this.workSpaceSuccess = true;
   console.log(this.launchUrl);
   }
   else{
   this.workSpaceSuccess = false;
   console.log(this.launchUrl);
   setTimeout(this.describeWorkspace(id), 200000);

   }
   //this.startWorkspace = resp;
   }).catch(err =>{
   console.log(err)
   });

   }*/


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

  showPlaygroundFiles(){
    this.getWorkspaceId(this.workspcId);

    /*//window.open( this.launchUrl,'_blank', 'location=yes,height=570,width=920,scrollbars=yes,status=yes');
     this.launchUrl = "https://pgfiles.altimetrik.com/files#/"+this.computerName+"/"+this.ADID+"/C:/PostSnap/Users/"+this.ADID+"/";
     window.open(this.launchUrl, '_blank');
     */
  }
  /*DESCRIBE WORKSPACE IS NOT AVAILABLE IN ORCHESTRATION- REQUEST FOR CHANGE IN NEXT SPRINT\-0*/

  getWorkspaceId(workspcId){

    console.log("getWorkspaceId")

    this.AuthService.getWorkspaceId(workspcId).then(resp => {


      this.reqData = resp;
      console.log(this.reqData);
      if(resp.status == 'success'){

        this.workSpaceData = JSON.parse(this.reqData['data']);

        this.workSpaceSuccess = true;

        console.log(this.workSpaceData, 'this.workSpaceData');

        this.workspaceId = this.workSpaceData.workSpaceId;

        this.computerName = this.workSpaceData.computerName;

        this.launchUrl = "https://pgfiles.altimetrik.com/files#/"+this.computerName+"/";/*+this.ADID+"/C:/PostSnap/Users/"+this.ADID+"/"*/

        window.open(this.launchUrl, '_blank');
      }
      else{
        console.log("workspaceId couldnot be retrieved");
      }
    }).catch(err=>{
      console.log(err)

      setTimeout(()=>{

      },6000);
    });
  }

  closeModal(modal){
    this.modal = '';
  }


  /*10/05/2017*/



  viewusecase(type){
    console.log('showusecase',type);

    if(type== 'tech'){
      this.Viewtechusecase = true;
    }
    else if (type =='bsns'){
      this.Viewbsnsusecase = true;
    }



  }
  closeusecase(){
    this.Viewtechusecase = false;
    this.Viewbsnsusecase = false;
  }

  getusecase(userId,eventId) {
    console.log("getusecaseinfo")
    this.AuthService.getUsecase(userId,eventId).then(resp => {

      if(resp){
        if(eventId == 2){
          this.techusecaseINFO = resp;
          console.log(this.techusecaseINFO.usecaseDescription, ' usecaseinfo');
        }
        else if(eventId == 3){
          this.bsnsusecaseINFO = resp;
          console.log(this.bsnsusecaseINFO.usecaseDescription, ' usecaseinfo');
        }



      }
      else{
        this.toastr.error("Unable to match use case")
      }

    }).catch(err => {
      console.log(err, 'error')
    })

  }

  //AWS POPOVER SCREEN


  clickedoutside(){
    this.showawspopover = false;
    console.log("clicked outside");
  }

  //AWS POPOVER SCREEN



  ccIndex(id){

    this.AuthService.getCCindex(id).then(resp=>{
      if(resp.status == 'error'){

      } else {
        console.log(resp)

        this.eventCapabilitiesList = resp.eventCapabilitiesList;

        this.eventCapabilitiesList.forEach(usrRole => {

          this.description.push({parameter:usrRole.parameter,eventCapabilityId:usrRole.eventCapabilityId,capabilityAreas:usrRole.capabilityAreas, "rating": '',"comment": ''});

        });

        console.log("this.description",id, this.description);
        this.capabilitesIndex = _.uniqBy(this.description, 'parameter');
        var array =[];
        console.log("levels",this.capabilitesIndex);
        for(let i =0;i< this.capabilitesIndex.length;i++){
          this.capabilitesIndex[i][this.capabilitesIndex[i].parameter ]= [];
          for(let j = 0; j<this.description.length;j++){
            if(this.description[j].parameter == this.capabilitesIndex[i].parameter ){

              array.push(this.description[j]);
              this.capabilitesIndex[i][this.capabilitesIndex[i].parameter ].push(this.description[j]);

            }
          }
        }


        console.log("sorted array",array);
        console.log(this.capabilitesIndex,'levelsssssss');
      }

    }).catch(err => {

    })
  }

  score(val,cmt,index) {

    for (var i in this.description) {

      if (this.description[i].eventCapabilityId == index) {
        this.description[i].rating = Math.round(val / 10);
        this.description[i].comment = cmt;
        break; //Stop this loop, we found it!
      }
      //  this.ccScore = this.ccScore+ Number(this.description[i].rating)
    }
    this.coreScore = 0
    this.digiScore = 0
    for (var i in this.description) {
      if(this.description[i].parameter == 'Core') {
        this.coreScore = this.coreScore + Number(this.description[i].rating);
      }
      else {
        this.digiScore = this.digiScore + Number(this.description[i].rating);
      }
    }
  }

  scoreBsn(val,cmt,index) {

    for (var i in this.description) {

      if (this.description[i].eventCapabilityId == index) {
        this.description[i].rating = Math.round(val / 10);
        this.description[i].comment = cmt;
        break; //Stop this loop, we found it!
      }
    }
    this.corebsnsScore = 0;
    this.digibsnsScore = 0;
    for (var i in this.description) {
      //TODO: expect more than one not just core and digital
      if(this.description[i].parameter == 'Core') {
        this.corebsnsScore = this.corebsnsScore + Number(this.description[i].rating);
      }
      else {
        this.digibsnsScore = this.digibsnsScore + Number(this.description[i].rating);
      }
    }
  }



  assignBusinessUsecaseScore_Comments(){
    this.bsnsEval = '';
    this.statusMsg = 'Reviewed'

    this.description = []
    console.log(this.eveDltsDesc);


    this.eveDltsDesc.forEach(usrRole => {

      if(usrRole.eventDtlsId == this.eveDlts[2].eventDtlsId) {


        if (usrRole.parameter != "HEAD_COACH") {

          this.description.push({
            parameter: usrRole.parameter,
            eventCapabilityId: usrRole.pgCapabilityCategoryMapping.pgEventCapability.eventCapabilityId,
            capabilityAreas: usrRole.pgCapabilityCategoryMapping.pgEventCapability.capabilityAreas,
            "rating": usrRole.rating,
            "comment": usrRole.comments
          });
        }
      }
    });



    this.corebsnsScore = 0
    this.digibsnsScore = 0
    for (var i in this.description) {
      if(this.description[i].parameter == 'Core') {
        this.corebsnsScore = this.corebsnsScore + Number(this.description[i].rating);
      }
      else {
        this.digibsnsScore = this.digibsnsScore + Number(this.description[i].rating);
      }
    }

    console.log(this.description,'bussiness usecase');
    this.cmtEnable = true;
  }

  assignTechnicalUsecaseScore_Comments(){
    this.description = []
    console.log(this.eveDltsDesc);


    this.eveDltsDesc.forEach(usrRole => {

      if(usrRole.eventDtlsId == this.eveDlts[1].eventDtlsId) {

        this.description.push({
          parameter: usrRole.parameter,
          eventCapabilityId: usrRole.pgCapabilityCategoryMapping.pgEventCapability.eventCapabilityId,
          capabilityAreas: usrRole.pgCapabilityCategoryMapping.pgEventCapability.capabilityAreas,
          "rating": usrRole.rating,
          "comment": usrRole.comments
        });
      }
    });



    this.coreScore = 0
    this.digiScore = 0
    for (var i in this.description) {
      if(this.description[i].parameter == 'Core') {
        this.coreScore = this.coreScore + Number(this.description[i].rating);
      }
      else {
        this.digiScore = this.digiScore + Number(this.description[i].rating);
      }
    }

    console.log(this.description);
    this.cmtEnable = true;
    this.techEval = '';
  }
  /*redunddant*/
  next(score){

    console.log(this.description)
    this.techEval = '';
  }
  nextDigit(score){

    this.techEval = 'Digital'
  }
  back(score){

    if(score == 'Digital') {

      this.techEval = 'Core';

    }
  }

  backbsns(score){
    if(score == 'Digital') {

      this.bsnsEval = 'Core';

    }
  }

  nextbsnsDigit(score){
    this.bsnsEval = '';
  }

  nextbsns(score){

    console.log(this.description)

    this.bsnsEval = 'Digital'
  }

  /*submitDigiBusiness(score){
   if(score == 'Core'){
   if(this.bsnsmindscore == 0 || this.bsnsadaptiveScore == 0 || this.bsnsfullstackScore == 0 || this.bsnstransdisScore == 0 || this.bsnsccScore == 0){

   this.bsnsEval = 'Core';

   }
   else{
   this.bsnsEval = 'Digital';
   }
   }
   else{
   if(this.bsnsmangAmbScore == 0 || this.bsnsculturalScore == 0 || this.bsnslearningScore == 0 || this.bsnscreativeInnovScore == 0 || this.bsnsorganisationValScore == 0){

   this.bsnsEval = 'Digital';

   }
   else{
   this.bsnsEval = '';
   }
   }


   }*/



  approve(status){

    console.log(status);

    var json =
      {
        "eventDtlsId":this.eveDlts[2].eventDtlsId,
        "userInfoMstrId":this.userData.userInfoMstr.userInfoMstrId,
        "coachId": this.empData.userInfoMstrId,
        "comment": this.bsnoverAllComment,
        "details": [
          {
            "description": this.description
          }
        ],
        "status":status
      }

    this.AuthService.updateCoachComments(json).then( responseData => {

      console.log(responseData)

      if(responseData.status == 'success'){

        this.userData.userInfoMstr.status = 'MAIN_PG_COACH_REVIEWED'
        this.eveDlts[2].eventOutput = status
        this.statusMsg = 'Review comments & Business Usecase Evaluation reviewed successfully'

        console.log(responseData)

      }
      else {

      }

    }).catch(err=>{

      console.log(err)
    });

  }


  submittechnicalfeedback(status){

    console.log(status);

    this.coachEvaluation = this.coachCandidateEvaluationService.getcoachCandidateTechnincalEvaluationData();

    var json =
      {
        "eventDtlsId":this.eveDlts[1].eventDtlsId,
        "userInfoMstrId":this.userData.userInfoMstr.userInfoMstrId,
        "coachId": this.empData.userInfoMstrId,
        "comment": this.coachEvaluation.overAllComment,
        "details": [
          {
            "description": this.coachEvaluation.description
          }

        ],
        "status":status

      }

    console.log(json)



    this.AuthService.updateCoachComments(json).then( responseData => {

      console.log(responseData)

      if(responseData.status == 'success'){

        this.userData.userInfoMstr.status = 'MINI_PG_COACH_APPROVED'

        if(status == 'MINI_PG_COACH_REJECTED'){

          this.eveDlts[1].eventOutput = status

          this.statusMsg = 'Review comments & Technical Usecase Evaluation reject successfully'

        }
        else {

          this.eveDlts[1].eventOutput = status
          this.statusMsg = 'Review comments & Technical Usecase Evaluation approved successfully'

        }
        /* this.coachCandidateEvaluationService.coachEvaluationCompletedThanks();

         this.getCoachCandidate(this.UserID);*/
        console.log(responseData)

      }
      else {

      }


    }).catch(err=>{

      console.log(err)
    });

    this.coachCandidateEvaluationService.coachEvaluationCompletedThanks();

    this.getCoachCandidate(this.UserID);



  }

  submitbusinessfeedback(feedbackBsns){

    console.log(feedbackBsns);
  }

  showCoreTech(techevalt){
    console.log("showcoretech::"+techevalt );
    this.techEval = techevalt;

  }

  showCoreBusn(techevalt){
    console.log("showcoretech::"+techevalt );
    this.bsnsEval = techevalt;

  }


  /*redunddant*/
}


