import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { LocalStorageService } from 'angular-2-local-storage';
import { AuthService } from '../services/auth.service';
import { WorkspaceService } from '../services/workspace.service';
import { Router } from '@angular/router';
import { NavigationService } from '../services/navigation/navigation.service';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { Utils } from 'app/utils';
import { TutorialService } from 'app/services/tutorial.service';


@Component({
  selector: 'app-technicalplayground',
  templateUrl: '../businessplayground/businessplayground.component.html',
  styleUrls: ['../businessplayground/businessplayground.component.scss']
})
export class TechnicalplaygroundComponent implements OnInit {

  seesionDetails = {};
  pageName = "Technical Usecase"
  tutorialName = 'candidate-technical-playground';

  @ViewChild('tutorialLauncher')
  tutorialModal: ElementRef;

  userData: {
    email: string,
    level: string,
    accessToken: string,
    fullName: string,
    loginType: string
  }
  initials: string;

  userDetails: {
    userInfoDtlsId: string,
    userInfoMstrId: string,
    adId: string,
    fullName: string,
    email: string,
    location: string,
    pgSkillTrackDtls: {
      pgSkillTrackMstr: {
        description: string,
        skillTrackName: string
      },
      description: string,
    },
    experienceInYrs: string,
    emailId: string,
    jobId: string,
    status: any,
    alternativeEmail: string,
    contactNumber: string,
    alternativeContact: string,
    governmentId: string,
  }

  computername: any;
  workSpaceData: {
    registrationCode: string,
    adId: string,
    workSpaceId: string,
    awsClientAccessUrl: string,
    errorBean: string,
    computerName: string
  }

  coach: {
    profilePic: string,
    fullName: string,
    position: string,
    role: string,
    email: string
  }

  error: any;
  workSpaceSuccess = false;
  isEmailError = false;
  isPwdError = false;
  isError = false;
  isLoading = false;
  errorMessage = '';
  userIcon = '';
  statusMsg: string
  statusView = false
  loginemailErrMsg = '';
  output: any;

  reqData: any
  cliUrl: any;
  UserID: string;

  userskilldetails;
  userINFODetails;
  scheduleMsg = '';
  name = '';
  fullName = '';
  empData = {};
  workspaceDirectoryId;
  sName = '';
  launchbuttonStatus: boolean;
  completebuttonStatus: boolean;
  workspaceData: any;
  usecaseINFO: any;

  userDiv = false
  constructor(protected localStorageService: LocalStorageService,
    private router: Router,
    private navigate: NavigationService,
    private AuthService: AuthService,
    private WorkspaceService: WorkspaceService,
    private toastr: ToastsManager,
    private tutorialService: TutorialService) {

    this.name = '';
    this.fullName = '';
    this.scheduleMsg = 'Schedule Assign this Candidate..';

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



    this.UserID = url.searchParams.get("uuid")


    var empData;
    empData = this.localStorageService.get('userInfo');
    console.log(this.localStorageService.get('userInfo'), 'localstorage');
    this.empData = empData

    console.log(this.empData, "userInfo Detailssssss")


    if (!this.UserID || this.UserID == null) {
      this.router.navigate(['dashboard']);
    }
    else {

      this.AuthService.getTestDetails({ userInfoMstrId: this.UserID }).then(resp => {

        console.log(resp, 'responseDataaaaa');
        if (resp.status == 'error') {

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

          this.userDetails = resp.infoMstr;
          this.userskilldetails = resp.infoMstr;

          this.userINFODetails = resp.infoDetails;

          this.fullName = this.userDetails.fullName;

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


          console.log(resp, 'userskilldetails');

          let event = resp.eventDetails.find(event => event.eventName == 'Launch Technical Use Case');
          let coach = resp.coachDetails.find(coach => coach.userInfoMstr.userInfoMstrId === event.coachId);

          this.coach = {
            profilePic: null,
            fullName: coach.fullName,
            position: coach.adId,
            role: coach.jobId,
            email: coach.emailId
          }

          this.getusecase(this.UserID, 2);
          if (this.userskilldetails.status == 'COACH_ASSIGNED') {

            this.launchbuttonStatus = false;
            this.completebuttonStatus = false;

          }
          else if (this.userskilldetails.status == 'MINI_PG_STARTED') {

            this.launchbuttonStatus = false;
            this.completebuttonStatus = false;

          }
          else {
            this.launchbuttonStatus = true;
            this.completebuttonStatus = true;
          }

        }




      }).catch(err => {

        console.log(err, 'error');
        // this.router.navigate(['dashboard'])
      })

    }



  }

  ngOnInit() {

    var OSName = "";
    if (navigator.appVersion.indexOf("Win") != -1) {
      OSName = "Windows";
      this.cliUrl = 'https://d2td7dqidlhjx7.cloudfront.net/prod/global/windows/Amazon+WorkSpaces.msi';
    }
    else if (navigator.appVersion.indexOf("Mac") != -1) {
      OSName = "MacOS";
      this.cliUrl = 'https://d2td7dqidlhjx7.cloudfront.net/prod/global/osx/WorkSpaces.pkg ';
    }
    else if (navigator.appVersion.indexOf("X11") != -1) {
      OSName = "UNIX";
      this.cliUrl = 'https://d2td7dqidlhjx7.cloudfront.net/prod/global/windows/Amazon+WorkSpaces.msi';
    }
    else if (navigator.appVersion.indexOf("Linux") != -1) {
      OSName = "Linux";
    }
    else {
      console.log('Your OS: ' + OSName);
    }
    console.log('Your OS: ' + OSName);
    this.showHelp();
  }



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




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

      if (resp) {
        this.usecaseINFO = resp;
        console.log(this.usecaseINFO.usecaseDescription, ' usecaseinfo');
        this.userDiv = true;
      }
      else {
        this.toastr.error("Unable to match use case")
      }

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

  }




  launch() {

    console.log("launch")

    this.workSpaceSuccess = false
    // console.log("launch-userData::"+this.userData);

    this.AuthService.getWorkspaceId({ adId: this.userINFODetails.adId }).then(resp => {

      //this.output = res;
      console.log("launch")


      console.log(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.workspaceDirectoryId = this.workSpaceData.workSpaceId;

     //   window.open(this.workSpaceData.awsClientAccessUrl, '_blank', 'location=yes,height=570,width=920,scrollbars=yes,status=yes');

        //this.describeWorkspace();

        if (this.userskilldetails.status == 'MINI_PG_STARTED') {

        }
        else {
          this.AuthService.candidateStatusUpdate({ candidateStatus: 'MINI_PG_STARTED', toId: this.userskilldetails.userInfoMstrId }).then(responseData => {

            console.log(responseData)

          }).catch(err => {

            console.log(err)
          });
        }

        this.launchbuttonStatus = false;
        this.completebuttonStatus = false;

      }
      else {
        this.launchbuttonStatus = false;
        this.completebuttonStatus = false;
        this.toastr.error('Workspace is not created');
      }
    }).catch(err => {
      console.log(err)
      this.isError = true;
      this.isLoading = false;
      this.error = err['message']
      setTimeout(() => {
        this.isError = false;
        //  this.router.navigate(['']);
      }, 6000);
    });



  }


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

  }

  complete() {
    console.log("complete")


    this.AuthService.candidateStatusUpdate({ candidateStatus: 'MINI_PG_COMPLETED', toId: this.userskilldetails.userInfoMstrId }).then(responseData => {

      console.log(responseData);

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

        document.getElementById('closeModal').click()
        this.toastr.success("Technical Usecase Completed Successfully and your test is pending review at the coach");
        this.router.navigate(['dashboard']);
      }
      this.launchbuttonStatus = true;
      this.completebuttonStatus = true;
      this.router.navigate(['dashboard']);
    }).catch(err => {

      console.log(err)
    });


    /* this.AuthService.getWorkspaceId({adId:this.userINFODetails.adId}).then(resp => {

       //this.output = res;
       console.log("launch")


       console.log(resp)

       this.reqData = resp

       console.log(this.reqData)

       this.workSpaceData = JSON.parse(this.reqData['data'])
       if(resp.status == 'success'){

         console.log(resp);
         console.log(this.workSpaceData);
         this.computername =  this.workSpaceData.computerName;
         this.workspaceDirectoryId = this.workSpaceData.workSpaceId;
         this.describeWorkspace();

         /!*this.WorkspaceService.getWorkspaceFiles({computerName:this.computername,sname:this.userINFODetails.adId}).then( responseData => {

          console.log(responseData);

          }).catch(err=>{

          console.log(err);

          });*!/

       }
       else{

       }
     }).catch(err=>{
       console.log(err)
       this.isError = true;
       this.isLoading = false;
       this.error = err['message']
       setTimeout(()=>{
         this.isError = false;
         //  this.router.navigate(['']);
       },6000);
     });*/


  }


  logout() {

    this.localStorageService.clearAll();
    localStorage.clear();
    this.router.navigate(['']);
  }

  num = 1;

  /*describeWorkspace(){

    this.WorkspaceService.describeWorkspaceById({sdirId:this.workspaceDirectoryId}).then(resp => {

      console.log("describeWorkspace:workspaceId:"+this.workspaceDirectoryId, this.num++);
      console.log("resp:"+resp);

      //this.computerName = resp;
      if(resp){

        this.computername = resp;
        this.WorkspaceService.saveComputerName(this.userINFODetails.adId, this.computername).then(resp => {
          console.log("saveComputerName");
          console.log("resp:saveComputerName"+resp);

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

      }
      else{

        this.callInterval();

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

  }*/

  describeWorkspace() {

    this.WorkspaceService.describeWorkspaceById({ sdirId: this.workspaceDirectoryId }).then(resp => {


      console.log("resp:", this.workspaceDirectoryId, resp);
      if (resp) {

        this.computername = resp;
        console.log("this.computername", this.computername);

        //save computername
        this.WorkspaceService.saveComputerName(this.userINFODetails.adId, this.computername).then(resp => {
          console.log("saveComputerName");
          console.log("resp:saveComputerName" + resp);

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

        //postsnap to fetch workspace files
        this.WorkspaceService.getWorkspaceFiles({ computerName: this.computername, sname: this.userINFODetails.adId }).then(responseData => {

          console.log(responseData);
          //update candidate status after fetching workspace files
          this.AuthService.candidateStatusUpdate({ candidateStatus: 'MINI_PG_COMPLETED', toId: this.userskilldetails.userInfoMstrId }).then(responseData => {

            console.log(responseData);

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

              this.toastr.success("Technical Usecase Completed Successfully and your test is pending review at the coach");
              this.router.navigate(['dashboard']);
            }
            this.launchbuttonStatus = true;
            this.completebuttonStatus = true;
            this.router.navigate(['dashboard']);
          }).catch(err => {

            console.log(err)
          });

        }).catch(err => {

          console.log(err);

        });

      }
      else {

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

  }

  startTutorial() {
    this.tutorialService.startTutorial(this.tutorialName);
  }

  showHelp() {
    this.tutorialModal.nativeElement.click();
  }
}
