import { Component, HostListener, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';
import { Router } from '@angular/router';
import { NavigationService } from '../services/navigation/navigation.service'
import { WorkspaceService } from '../services/workspace.service';
import { Utils } from 'app/utils';
import { CANDIDATE_STATUS, CANDIDATE_STATUS_NAMES } from 'app/models/candidateStatus';
import { UserService } from 'app/services/user.service';
import { environment } from '../../environments/environment.dev';
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css'],

})
export class DashboardComponent {

  sessionDetails: any;
  name: string;
  mettleStatus: string;
  errorMessage: string;
  isDashBoard = false;
  output: any;
  reqData: any;
  dashBoards: any[];
  workspaceInfo: any;

  circleModal: string;
  circleModalClosedByUser: boolean = false;
  imageUrl = environment.imageUrl;
  get circleModalShow() {
    return (this.circleModal && !this.circleModalClosedByUser);
  }

  resultData: {
    candidate: {
      testStatus: {},
      registration: {},
      email: string[]
    },
    error: string[],
    status: string[]
    testStatus: string[]
  };
  role = 'CANDIDATE';
  userData: any
  usermasterId;
  CandidateData: boolean
  mettlEvts: boolean
  initials: string

  completeText =  {
      "Launch Primary Skills Evaluation": "Primary Skill Evaluation Completed",
      "Launch Technical Use Case": "Technical Use Case Completed",
      "Launch Business Use Case": "Business Use Case Completed"
    }

  constructor(protected localStorageService: LocalStorageService,
    private AuthService: AuthService,
    private router: Router,
    private navigate: NavigationService,
    private WorkspaceService: WorkspaceService,
    private userService: UserService) {

    this.CandidateData = false;
    this.technicalDisabled = true;
    this.mettlEvts = true;
    this.isDashBoard = false;
    var reqData = {};
    this.reqData = this.localStorageService.get('authToken');
    this.name = this.reqData['fullName'];


    this.AuthService.dashBoardDetails(this.reqData).then(resp => {
      this.output = resp;

      if (this.output.status == 'error') {
        this.CandidateData = true;
        this.isDashBoard = false;
        this.errorMessage = this.output.message;
        //  console.log(JSON.parse(this.output.message['body']),'elseIf')

      }
      else if (this.output) {
        this.output = JSON.parse(resp);
        // console.log(this.output);
        console.log(this.output.eventDetails);
        console.log(this.output.eventDetails[0].eventSts);
        // this.output.eventDetails[0].testLink = null;
        this.userData = this.output.infoDetails
        this.usermasterId = this.output.infoMstr.userInfoMstrId;
        console.log(this.userData, 'userDetailsssssssssssss')
        console.log(this.userData.status, 'userDetailsssssssssssss')

        this.mettleStatus = this.output.eventDetails[0].eventSts;
        this.isDashBoard = true;
        this.dashBoards = this.output.eventDetails
        this.CandidateData = true;

        this.initials = Utils.Initials(this.userData.fullName);

        console.log('dashboard', 'seting userInfo');
        this.userService.setUserInfo({
          accessToken: this.localStorageService.get('token'),
          userInfoMstrId: this.usermasterId
        });

        this.updateCircleModal();
      } else {

        console.log(this.output, 'else')
      }


    }).catch(err => {
      console.log(err)
      this.CandidateData = true;
      this.isDashBoard = false;
      this.errorMessage = err.message;

    });

  }

  ngOnInit() {
    this.technicalDisabled = true;
    this.isDashBoard = false;
    var reqData = {};

    this.reqData = this.localStorageService.get('authToken');
    this.name = this.reqData['fullName'];

    /*
    window.onfocus = (e) => {
      console.log('Got focus');

      if (this.userData.userInfoMstr.status == 'METTL_SCHEDULED') {

      this.AuthService.dashBoardDetails(this.reqData).then(resp => {
        this.output = resp;
        console.log(this.output)


        if (this.output.status == 'error') {
          this.isDashBoard = false;
          this.errorMessage = this.output.message;
          //  console.log(JSON.parse(this.output.message['body']),'elseIf')

        }
        else if (this.output) {
          this.output = JSON.parse(resp);
          console.log(this.output);
          console.log(this.output.eventDetails);
          // this.output.eventDetails[0].testLink = null;
          this.mettleStatus = this.output.eventDetails[0].eventSts;
          this.isDashBoard = true;
          this.dashBoards = this.output.eventDetails
        }
        else {

          console.log(this.output, 'else')
        }


      }).catch(err => {
        console.log(err)
        console.log(err)
        this.isDashBoard = false;
        this.errorMessage = err.message;

      });
      this.AuthService.getResultDetails(this.reqData).then(resp => {
        this.output = resp;
        console.log(this.output, 'else')
      }).catch(err => {
        console.log(err)

      })

    }
    };
    */

  }

  technicalActive = '';
  businessSelected = '';
  userIcon = '';
  technicalDisabled = true;
  businessDisabled = true;
  primaryScore = null;
  technicalScore = null;
  businessScore = null;
  setActive = true;
  timewarp = 1;
  goldenkey = 0;
  components = 3;
  filteredLeader = 'overall';
  leaderboard = [
    {
      "img": this.imageUrl+"/assets/img/dashboard/profile-pic.jpg",
      "name": "John Doe",
      "score": "98P"
    },
    {
      "img": this.imageUrl+"/assets/img/dashboard/profile-pic.jpg",
      "name": "John Doe",
      "score": "98P"
    },
    {
      "img": this.imageUrl+"/assets/img/dashboard/profile-pic.jpg",
      "name": "John Doe",
      "score": "98P"
    },
    {
      "img": this.imageUrl+"/assets/img/dashboard/profile-pic.jpg",
      "name": "John Doe",
      "score": "98P"
    },
    {
      "img": this.imageUrl+"/assets/img/dashboard/profile-pic.jpg",
      "name": "John Doe",
      "score": "98P"
    },
    {
      "img": this.imageUrl+"/assets/img/dashboard/profile-pic.jpg",
      "name": "John Doe",
      "score": "98P"
    }
  ];

  ScorePrimary = {};
  ScoreTechnical = {};
  ScoreBusiness = {};
  goToPrimary(evtName, link) {
    console.log("redirect to primary skills" + evtName);
    if (evtName == 'Launch Primary Skills Evaluation') {
      this.mettlEvts = false;
      window.open(link, '_blank');
      // this.navigate.goToTechnicalTestPage();
    }
    else if (evtName == 'Launch Technical Use Case') {

      window.location.href = window.location.origin + '/technicalPlayground?' + 'uuid=' + this.usermasterId;

    } else if (evtName == 'Launch Business Use Case') {
      window.location.href = window.location.origin + '/businessPlayground?' + 'uuid=' + this.usermasterId;
    }
    else {
      //  this.navigate.goToPrimaryTestPage();
      window.open(evtName, '_blank');
    }

  }

  getPrimaryScore(score) {

    //api call to fetch primary test score.
    this.setActive = score.setActive;
    this.technicalActive = score.technicalActive;
    this.technicalDisabled = score.technicalDisabled;
    this.businessDisabled = score.businessDisabled;
    this.primaryScore = score.primaryScore;
    /*this.timewarp = score.timewarp;
     this.goldenkey = score.goldenkey;
     this.components = score.components;*/

  }

  goToTechnical() {
    console.log("redirect to technical test page");
    this.navigate.goToTechnicalTestPage();
  }

  getTechnicalScore(score) {
    this.businessSelected = score.businessSelected;
    this.businessDisabled = score.businessDisabled;
    this.technicalScore = score.technicalScore;
    /*this.timewarp = score.timewarp;
     this.goldenkey = score.goldenkey;
     this.components = score.components;*/
  }

  goToBusiness() {
    console.log("redirect to business test page");
    this.navigate.goToBusinessTestPage();
  }

  getBusinessScore(score) {
    this.businessScore = score.businessScore;
    /*this.timewarp = score.timewarp;
     this.goldenkey = score.goldenkey;
     this.components = score.components;*/

  }
  getLeaderboard(branch) {

    //take user to primary skills test page from here
    console.log("redirect to primary skills" + branch);

    this.filteredLeader = branch;
  }

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

  getResultMettle() {
    this.reqData = this.localStorageService.get('authToken');
    this.AuthService.getResultDetails(this.reqData).then(resp => {
      this.output = resp;

      this.resultData = JSON.parse(this.output);
      //window.location.href = this.resultData.candidate.testStatus['htmlReport']
      window.open(this.resultData.candidate.testStatus['htmlReport'], '_blank');
    }).catch(err => {
      console.log(err)
    })
  }

  mettleComplete() {

    this.AuthService.getResultDetails(this.reqData).then(resp => {
      this.output = resp;
      console.log(this.output, 'else')
      // window.location.href = window.location.origin+'/dashboard'

      this.AuthService.dashBoardDetails(this.reqData).then(resp => {
        this.output = resp;

        if (this.output.status == 'error') {
          this.CandidateData = true;
          this.isDashBoard = false;
          this.errorMessage = this.output.message;
          //  console.log(JSON.parse(this.output.message['body']),'elseIf')

        }
        else if (this.output) {

          this.output = JSON.parse(resp);
          // console.log(this.output);
          console.log(this.output.eventDetails);
          console.log(this.output.eventDetails[0].eventSts);
          // this.output.eventDetails[0].testLink = null;
          this.userData = this.output.infoDetails
          console.log(this.userData, 'userDetailsssssssssssss')
          console.log(this.userData.status, 'userDetailsssssssssssss')

          this.mettleStatus = this.output.eventDetails[0].eventSts;
          this.isDashBoard = true;
          this.dashBoards = this.output.eventDetails
          this.CandidateData = true;
          this.mettlEvts = true;
        } else {

          console.log(this.output, 'else')
        }


      }).catch(err => {
        console.log(err)
        this.CandidateData = true;
        this.isDashBoard = false;
        this.errorMessage = err.message;

      });

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

    })
  }

  startWorkspace() {

    this.workspaceInfo = this.WorkspaceService.getWorkspaceId();

    this.WorkspaceService.startWorkspace({ Id: this.workspaceInfo.workspaceId }).then(resp => {

      console.log("Workspace Started");
      console.log("resp:" + resp);
      if (resp) {

      } else {

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

    });
  }

  stopWorkspace() {
    this.WorkspaceService.stopWorkspaces({ Id: this.workspaceInfo.workspaceId }).then(resp => {

      console.log("Workspace Stopped");
      console.log("resp:" + resp);
      if (resp) {

      } else {

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

    });
  }

  terminateWorkspace() {
    this.WorkspaceService.terminateWorkspaces({ Id: this.workspaceInfo.workspaceId }).then(resp => {

      console.log("Workspace terminated");
      console.log("resp:" + resp);
      if (resp) {

      } else {

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

    });
  }

  rebuildWorkspace() {
    this.WorkspaceService.rebuildWorkspaces({ Id: this.workspaceInfo.workspaceId }).then(resp => {

      console.log("Workspace rebuilt");
      console.log("resp:" + resp);
      if (resp) {

      } else {

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

    });
  }

  private updateCircleModal() {
    switch (this.userData.userInfoMstr.status) {
      case CANDIDATE_STATUS_NAMES.TA_APPROVED:
      case CANDIDATE_STATUS_NAMES.METTL_SCHEDULED:
      case CANDIDATE_STATUS_NAMES.METTL_COACH_ASSIGNED:
        this.circleModal = 'journey';
        break;

      case CANDIDATE_STATUS_NAMES.COACH_ASSIGNED:
      case CANDIDATE_STATUS_NAMES.MINI_PG_STARTED:
        this.circleModal = 'technical';
        break;

      case CANDIDATE_STATUS_NAMES.MAIN_PG_COACH_ASSIGNED:
      case CANDIDATE_STATUS_NAMES.MAIN_PG_STARTED:
        this.circleModal = 'busisess';
        break;

      default:
        this.circleModal = null;
        break;
    }
  }

  circleModalClick() {
    this.circleModalClosedByUser = true;
  }
}
