import { Component, OnInit, Input } from '@angular/core';
import { InfoDetails } from 'app/models/candidate-dashboard-response/info-details';
import { EventDetail } from 'app/models/candidate-dashboard-response/event-detail';
import { CandidateDashboardResponse } from 'app/models/candidate-dashboard-response/candidate-dashboard-response';
import {AuthService} from 'app/services/auth.service';
import _ from "lodash";
import {MAP_CANDIDATE_STATUS, CANDIDATE_STATUS} from 'app/models/candidateStatus';

@Component({
  selector: 'app-candidate-business-skills',
  templateUrl: './candidate-business-skills.component.html',
  styleUrls: ['./candidate-business-skills.component.css']
})
export class CandidateBusinessSkillsComponent implements OnInit {

  _candidateDashboard: CandidateDashboardResponse;
  _candidate: InfoDetails;
  _role: any;
  _eventDetails: EventDetail;

  static TEST_YET_TO_START = 'MAIN_PG_COACH_ASSIGNED';
  static TEST_IN_PROGRESS = 'MAIN_PG_STARTED';
  static BUSINESS_TEST_COMPLETED = 'MAIN_PG_COMPLETED';



  access: any;
  eventCapabilitiesList=[];
  description = [];
  capabilitesIndex : [
    {
      capabilityAreas: string;
      comment: ""
      eventCapabilityId: number;
      parameter: string
      rating: ""
      commonCriteria:any[];
      totalScore:number;
      score:number;
    }
    ];

  eventDetailsArray= [ ];
  workSpaceData:{
    registrationCode:string,
    adId:string,
    workSpaceId:string,
    awsClientAccessUrl:string,
    errorBean:string,
    computerName:string
  };
  disabled = false;
  max = 100;
  min = 0;
  step = 1;
  value = 0;
  vertical = false;
  techusecaseINFO:any;
  showUseCaseModal:boolean;
  showWorkspaceInfo:boolean;
  readaccess:boolean;

  get candidateDashboard() {
    return this._candidateDashboard;
  }

  @Input('candidate')
  set candidateDashboard(cd) {
    this._candidateDashboard = cd;

    this.setAccess();
  }

  get role() {
    return this._role;
  }

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

  get eventDetails() {
    return this._eventDetails;
  }

  @Input()
  set eventDetails(eventDetails) {
    this._eventDetails = eventDetails;
    //this.setAccess();
  }

  constructor(private authservice:AuthService) { }

  ngOnInit() {

  }

  // TODO: set values to show hide parts of the view depending on the candidate and role of the user
  private setAccess() {
    this.access = {

      testInProgress: this.testInProgress(),
      testTobeStarted:this.testToStart(),
      businessTestCompleted:this.testCompleted(),
      showPlaygroundFiles:this.showPlaygroundFiles(),
      showUseCase:this.showUseCaseText()
    };
  }

  private testInProgress() {
    return this.candidateDashboard.infoMstr.status === CandidateBusinessSkillsComponent.TEST_IN_PROGRESS;
  }

  private testCompleted(){
    var val = this.candidateDashboard.infoMstr.status;


    if(MAP_CANDIDATE_STATUS[val] === CANDIDATE_STATUS.MAIN_PG_COMPLETED){

      this.authservice.getCCindex(3).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", this.description);
          this.capabilitesIndex = _.uniqBy(this.description, 'parameter');

          console.log("levels",this.capabilitesIndex);

          for(let i =0;i< this.capabilitesIndex.length;i++){

            this.capabilitesIndex[i].commonCriteria= [];

            for(let j = 0; j<this.description.length;j++){

              if(this.description[j].parameter == this.capabilitesIndex[i].parameter ){


                this.capabilitesIndex[i].commonCriteria.push(this.description[j]);
                this.capabilitesIndex[i].totalScore=0;
              }
            }
          }
          this.readaccess = false;
          console.log(this.capabilitesIndex,'levelsssssss');
          return true;

        }

      }).catch(err => {

      })

    }
    else if(MAP_CANDIDATE_STATUS[val] > CANDIDATE_STATUS.MAIN_PG_COMPLETED){
      console.log(this.candidateDashboard,"this._candidateDashboard");


      this.candidateDashboard.eventDetailsDesc.forEach(usrRole => {

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

          if (usrRole.parameter != "HEAD_COACH") {
            this.eventDetailsArray.push({
              parameter: usrRole.parameter,
              eventCapabilityId: usrRole.pgCapabilityCategoryMapping.pgEventCapability.eventCapabilityId,
              capabilityAreas: usrRole.pgCapabilityCategoryMapping.pgEventCapability.capabilityAreas,
              "rating": usrRole.rating,
              "comment": usrRole.comments,
              "score": usrRole.score
            });
          }
        }

        this.capabilitesIndex = _.uniqBy(this.eventDetailsArray, 'parameter');

        console.log("levels",this.capabilitesIndex);

        for(let i =0;i< this.capabilitesIndex.length;i++){

          this.capabilitesIndex[i].commonCriteria= [];

          for(let j = 0; j<this.eventDetailsArray.length;j++){

            if(this.eventDetailsArray[j].parameter == this.capabilitesIndex[i].parameter ){


              this.capabilitesIndex[i].commonCriteria.push(this.eventDetailsArray[j]);
              this.capabilitesIndex[i].totalScore=0;
            }
          }
        }

        console.log(this.capabilitesIndex,'levelsssssss');
        this.readaccess = true;
        return true;
      });

      console.log("this.eventDetailsArray", this.eventDetailsArray);

    }


  }

  private testToStart(){
    return this.candidateDashboard.infoMstr.status === CandidateBusinessSkillsComponent.TEST_YET_TO_START;
  }

  private showPlaygroundFiles(){
    return MAP_CANDIDATE_STATUS[this.candidateDashboard.infoMstr.status] >= CANDIDATE_STATUS.MAIN_PG_COMPLETED && MAP_CANDIDATE_STATUS[this.candidateDashboard.infoMstr.status] <= CANDIDATE_STATUS.MAIN_PG_COACH_REVIEWED;
  }


  private showUseCaseText(){
    return MAP_CANDIDATE_STATUS[this.candidateDashboard.infoMstr.status] >= CANDIDATE_STATUS.MAIN_PG_COACH_ASSIGNED;
  }

  //todo: improvise the structure to not to make api calls here

  //getusecase(userId,eventId) {
  getusecase() {
    console.log("getusecaseinfo")
    var userId = this.candidateDashboard.infoMstr.userInfoMstrId;
    var eventId = 3;
    this.techusecaseINFO = 'djfaldfkjalfdjldakf';
    this.showUseCaseModal = true;
    this.authservice.getUsecase(userId,eventId).then(resp => {

      if(resp){

        this.techusecaseINFO = resp;
        this.showUseCaseModal = true;
        this.showWorkspaceInfo = false;
        console.log(this.techusecaseINFO.usecaseDescription, ' usecaseinfo');


      }
      else{

      }

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

  }
  closeUseCase(){
    this.showUseCaseModal = false;
    this.showWorkspaceInfo = false;
  }

  LaunchWorkspace(){
    window.open(this.workSpaceData.awsClientAccessUrl, '_blank');
  }
  getWorkspaceInfo(){

    this.authservice.getWorkspaceId({adId:this._candidateDashboard.infoDetails.adId}).then(resp => {



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

        this.workSpaceData = JSON.parse(resp['data']);
        this.showWorkspaceInfo = true;
        this.showUseCaseModal = false;
        console.log(this.workSpaceData, 'this.workSpaceData');

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

      setTimeout(()=>{

      },6000);
    });

  }

}
