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 { MAP_CANDIDATE_STATUS, CANDIDATE_STATUS } from 'app/models/candidateStatus';
import _ from 'lodash';

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

  static TEST_YET_TO_START = 'COACH_ASSIGNED';
  static TEST_IN_PROGRESS = 'MINI_PG_STARTED';
  static TECHNICAL_TEST_COMPLETED = 'MINI_PG_COMPLETED';

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

  access: any;
  eventCapabilitiesList = [];
  description = [];
  candiateStatus: string;

  capabilitesIndex: [
    {
      capabilityAreas: string;
      comment: '';
      eventCapabilityId: number;
      parameter: string
      rating: '';
      commonCriteria: any[];
      totalScore: number;
      totalRating: 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.candiateStatus = this._candidateDashboard.infoMstr.status;
    this.setAccess();
  }

  get role() {
    return this._role;
  }

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

  get eventDetails() {
    return this._eventDetails;
  }

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

  constructor(private authservice: AuthService) {
  }

  ngOnInit() {
  }

  private setAccess() {
    this.access = {
      testInProgress: this.testInProgress(),
      testTobeStarted: this.testToStart(),
      technicalTestCompleted: this.testCompleted(),
      showPlaygroundFiles: this.showPlaygroundFiles(),
      showUseCase: this.showUseCaseText()
    };
  }

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

  private testCompleted() {
    const val = this.candidateDashboard.infoMstr.status;
    if (MAP_CANDIDATE_STATUS[val] === CANDIDATE_STATUS.MINI_PG_COMPLETED) {
      this.authservice.getCCindex(2).then(resp => {
        if (resp.status !== 'error') {
          this.eventCapabilitiesList = resp.eventCapabilitiesList;
          this.eventCapabilitiesList.forEach(usrRole => {
            this.description.push({
              parameter: usrRole.parameter,
              eventCapabilityId: usrRole.eventCapabilityId,
              capabilityAreas: usrRole.capabilityAreas,
              'rating': '',
              'comment': ''
            });
          });
          this.capabilitesIndex = _.uniqBy(this.description, 'parameter');
          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.capabilitesIndex[i].totalRating = 0;
              }
            }
          }
          this.readaccess = false;
        }
      }).catch(err => {
        console.log(err);
      });
      return true;
    } else if (MAP_CANDIDATE_STATUS[val] > CANDIDATE_STATUS.MINI_PG_COMPLETED) {
      this.readaccess = true;
      this.candidateDashboard.eventDetailsDesc.forEach(usrRole => {
        if (usrRole.eventDtlsId === this._candidateDashboard.eventDetails[1].eventDtlsId) {
          this.eventDetailsArray.push({
            parameter: usrRole.parameter,
            eventCapabilityId: usrRole.pgCapabilityCategoryMapping.pgEventCapability.eventCapabilityId,
            capabilityAreas: usrRole.pgCapabilityCategoryMapping.pgEventCapability.capabilityAreas,
            'rating': usrRole.rating,
            'score': usrRole.score,
            'comment': usrRole.comments
          });
        }
        this.capabilitesIndex = _.uniqBy(this.eventDetailsArray, 'parameter');
        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;
            }
          }
        }
      });
      return true;
    }
  }

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

  private showPlaygroundFiles() {
    return MAP_CANDIDATE_STATUS[this.candidateDashboard.infoMstr.status] >= CANDIDATE_STATUS.MINI_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.COACH_ASSIGNED;
  }

  getusecase() {
    console.log("getusecaseinfo")
    var userId = this.candidateDashboard.infoMstr.userInfoMstrId;
    var eventId = 2;
    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');
        this.showWorkspaceInfo = true;
      }
    }).catch(err => {
      console.log(err);
    });

  }
}
