import { Component, OnInit,Input, Output, EventEmitter,ViewChild, AfterViewInit  } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import { Utils } from 'app/utils';
import {AuthService} from 'app/services/auth.service';
import {WorkspaceService} from 'app/services/workspace.service';
import {CoachCandidateEvaluationService} from 'app/coach/shared/service/coach-candidate-evaluation.service';
import { MatStepper } from '@angular/material';
import { LocalStorageService } from 'angular-2-local-storage';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { CandidateDashboardResponse } from 'app/models/candidate-dashboard-response/candidate-dashboard-response';
import {MAP_CANDIDATE_STATUS, CANDIDATE_STATUS} from 'app/models/candidateStatus';
import {Router} from "@angular/router";

@Component({
  selector: 'app-cc-index',
  templateUrl: './ccindex.component.html',
  styleUrls: ['./ccindex.component.scss']

})
export class CcindexComponent implements OnInit, AfterViewInit  {

  @ViewChild('stepper') stepper : MatStepper;
  _role : any;
  ngAfterViewInit() {


    if(this.noWrite){

      this.stepper.linear = false;

      if(this.event === 'technicalUseCase' )
        this.stepper.selectedIndex = this.ccIndexCapabilites.length;
      if(this.event === 'businessUseCase' )
        this.stepper.selectedIndex = this.ccIndexCapabilites.length;

    }
    else{
      this.stepper.linear = true;
      this.stepper.selectedIndex = 0;
    }

  }


  coachCandidateEvaluationObject = {description: [],event:'',overAllComment:''};
  _candidateDashboard: CandidateDashboardResponse;
  nowrite : boolean;
  eVent : string;

  @Input()
  ccIndexCapabilites:any[];

  /* @Input()
   role:any;*/

  get noWrite(){
    return this.nowrite;
  }

  @Input()
  set noWrite(r){
    this.nowrite = r;

  }
  @Input()
  set role(r){
    this._role = r;

  }

  get event(){
    return this.eVent;
  }

  @Input()
  set event(r){
    this.eVent = r;

  }

  miniPgCoachApproved: boolean;
  mainPgCoachReviewed: boolean;
  mainPgCoachApproved = false;
  mainPgCoachRejected = false;

  get candidateDashboard() {
    return this._candidateDashboard;
  }

  @Input('candidate')
  set candidateDashboard(cd) {

    this._candidateDashboard = cd;
    var val = this._candidateDashboard.infoDetails.userInfoMstr.status;

    if( MAP_CANDIDATE_STATUS[val] >= CANDIDATE_STATUS.MINI_PG_COACH_APPROVED && this.eVent === 'technicalUseCase'){
      this.miniPgCoachApproved= true;
    }
    else if(MAP_CANDIDATE_STATUS[val] == CANDIDATE_STATUS.MAIN_PG_COACH_REVIEWED && this.eVent === 'businessUseCase'){
      this.mainPgCoachReviewed = true;
      this.miniPgCoachApproved= true;

    }
    else if(MAP_CANDIDATE_STATUS[val] == CANDIDATE_STATUS.MAIN_PG_MANAGER_APPROVED && this.eVent === 'businessUseCase'){
      this.mainPgCoachApproved = true;
      this.miniPgCoachApproved= true;
    }
    else if(MAP_CANDIDATE_STATUS[val] == CANDIDATE_STATUS.MAIN_PG_MANAGER_REJECTED && this.eVent === 'businessUseCase'){
      this.mainPgCoachRejected = true;
      this.miniPgCoachApproved= true;

    }


  }

  comment:string;

  scorecard=[0,1,2,3,4,5,6,7,8,9,10];
  autoTicks = false;

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

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

  successScreen:boolean;
  candidateCompleted:boolean;

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


  firstFormGroup: FormGroup;
  secondFormGroup: FormGroup;

  constructor(protected localStorageService: LocalStorageService,
              private _formBuilder: FormBuilder, private AuthService:AuthService,
              private toastr: ToastsManager,
              private WorkspaceService:WorkspaceService,
              private router:Router,
              private coachCandidateEvaluationService:CoachCandidateEvaluationService) {


    var empData
    empData = this.localStorageService.get('userInfo');
    this.empData = empData
    console.log(this.empData,"userInfoDtls CC-Index Detailssssss")


    if(window.location.origin == 'http://localhost:8080'){

      this.empData = {
        accessToken: '',
        loginType: '',
        fullName: 'Sabash LS',
        firstName: 'sabash',
        userInfoMstrId: 2,
        roleName: 'HEAD_COACH',
        roles: [1],
        skills: [1,2],
        location: 1
      };

    }
    else {

    }


  }



  ngOnInit() {

    this.firstFormGroup = this._formBuilder.group({
      firstCtrl: ['', Validators.required]
    });

    this.coachCandidateEvaluationService.show_thankyou_sent.subscribe(value => {
      this.successScreen = value;
    });



    for (var i in this.ccIndexCapabilites) {
      this.ccIndexCapabilites[i].totalScore=0;
      this.ccIndexCapabilites[i].totalRating=0;
      for(var j in this.ccIndexCapabilites[i].commonCriteria){
        this.ccIndexCapabilites[i].totalScore = this.ccIndexCapabilites[i].totalScore + Number( this.ccIndexCapabilites[i].commonCriteria[j].score);
        this.ccIndexCapabilites[i].totalRating = this.ccIndexCapabilites[i].totalRating + Number( this.ccIndexCapabilites[i].commonCriteria[j].rating);
      }
    }

    for(var i in this.ccIndexCapabilites){

      this.score = this.score + this.ccIndexCapabilites[i].totalScore;
    }


  }

  scoreBsn(val,cmt,index) {

    console.log("val,cmt,index,rowcount,commonIndex ",val,cmt,index);
    for (var i in this.ccIndexCapabilites) {


      for(var j in this.ccIndexCapabilites[i].commonCriteria){
        if (this.ccIndexCapabilites[i].commonCriteria[j].eventCapabilityId == index) {
          this.ccIndexCapabilites[i].commonCriteria[j].rating = Math.round(val / 10);
          this.ccIndexCapabilites[i].commonCriteria[j].comment = cmt;
          break; //Stop this loop, we found it!
        }
      }

    }

    for (var i in this.ccIndexCapabilites) {
      this.ccIndexCapabilites[i].totalScore=0;
      for(var j in this.ccIndexCapabilites[i].commonCriteria){
        this.ccIndexCapabilites[i].totalScore = this.ccIndexCapabilites[i].totalScore + Number( this.ccIndexCapabilites[i].commonCriteria[j].rating);
      }
    }

    this.score = 0;

    for(var i in this.ccIndexCapabilites){

      this.score = this.score + this.ccIndexCapabilites[i].totalScore;
    }

  }
  approve($event){

    var event = '2';
    var overAllComment = this.comment;

    this.coachCandidateEvaluationObject= {description: [],event:'',overAllComment:''};

    for( var i in this.ccIndexCapabilites){
      for(var j in this.ccIndexCapabilites[i].commonCriteria) {
        let commonCriteria = {...this.ccIndexCapabilites[i].commonCriteria[j]}; //copied object
        delete commonCriteria.commonCriteria; //deleting

        this.coachCandidateEvaluationObject.description.push(commonCriteria);

      }
    }

    this.coachCandidateEvaluationObject.description.sort((a, b) => a.eventCapabilityId - b.eventCapabilityId);
    this.coachCandidateEvaluationObject.event= event;
    this.coachCandidateEvaluationObject.overAllComment=overAllComment;


    console.log(this.coachCandidateEvaluationObject,"coachCandidateEvaluationObject")
    this.coachCandidateEvaluationService.setcoachCandidateTechnincalEvaluationData(this.coachCandidateEvaluationObject);



  }

  lastApprove(status,comments){


    console.log(comments, status,'Comments & Status');
    console.log(this.empData,"userInfoDtls CC-Index Detailssssss")
    console.log("LAST UPDATE COMMENTS AND STATUS API IS PENDING");

    var json =
      {
        "candidateStatus": status,

        "headCoachComment": comments,

        "toId": this._candidateDashboard.infoDetails.userInfoMstr.userInfoMstrId,
        "fromId": this.empData.userInfoMstrId

      }

    console.log(json)

    this.AuthService.candidateStatusUpdate(json).then( responseData => {
      console.log(responseData)


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


        if(status == 'MAIN_PG_MANAGER_REJECTED'){


          //this.statusMsg = 'Review comments & Technical Usecase Evaluation reject successfully'
          this.toastr.success("Review comments & Business Usecase Evaluation rejected successfully");

        }
        else {


          //this.statusMsg = 'Review comments & Technical Usecase Evaluation approved successfully'
          this.toastr.success("Review comments & Business Usecase Evaluation approved successfully");

        }
        this.terminateWorkspace(this._candidateDashboard.infoDetails.adId)
        this.router.navigate(['pgm/landing'])

      }
      else {
      }

    }).catch(err=>{

      console.log(err)
    });

  }

  getInitial(param:string):string {
    return Utils.Initial(param);
  }

  terminateWorkspace(adId){

    console.log("getWorkspaceId")

    this.AuthService.getWorkspaceId({adId:adId}).then(response => {
      console.log(response, "getWorkspaceId")
      if(response.status == 'success'){

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

          if(resp) {

            this.WorkspaceService.deleteWorkspace({sname: adId}).then(respData => {
              console.log(respData);
              // this.toastr.success("Candidate status updated and workspace termiated")

            }).catch(err => {
              console.log(err);
            });
          }
          else {
            console.log("workspace couldnot be terminated");
          }
        }).catch(err => {
          console.log(err);
        });
      }
      else {
        console.log("workspaceId couldnot be retrieved");
      }
    }).catch(err => {
      console.log(err);
    });


  }


  resetStepper($event, stepper: MatStepper){
    stepper.selectedIndex = $event;
  }

  _finished($event){

    this.router.navigate(['coach/landing']);
    this.successScreen= false;
    this.coachCandidateEvaluationService.coachEvaluationCompletedThanksClose();

  }
  callMethod(){
    var val = this.ccIndexCapabilites.length;

    console.log(this.ccIndexCapabilites.length,'this.ccIndexCapabilites.length')

    this.stepper.selectedIndex =val;


  }



}
