import { Component, OnInit, Input } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';
import {Router, ActivatedRoute} from '@angular/router';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import {URLSearchParams} from "@angular/http";
import { NavBarService } from '../../pgm/pgm.service';
import { DomSanitizer } from '@angular/platform-browser';
import _ from "lodash";
import {el} from "@angular/platform-browser/testing/src/browser_util";
import { environment } from '../../../environments/environment.dev';
@Component({
  selector: 'app-pgm-candidate',
  templateUrl: './pgm-candidate.component.html',
  styleUrls: ['./pgm-candidate.component.scss']
})
export class PgmCandidateComponent implements OnInit {

  @Input() assessmentId: string='';
  @Input() primarySkill: string='';
  @Input() secondarySkill: string='';



  assignBtnEnable = false
  viewProfile = true
  userIcon :string
  divExpand = true
  dashBoards: any[];
  isError = false;
  isSuccess = false;
  errorMessage : any;
  successMessage : any;
  onboardRjct : boolean
  scheduleMsg : any;
  mettleStatus:boolean;
  mettleDlsStatus:boolean;


  UserID : string;
  PGMCandidateDtls = false
  userData:{
    userInfoDtlsId: string,
    adId: string,
    fullName:string,
    email:string,
    location:string,
    profileName:string,
    profileId:string,
    linkedInId:string,
    googleId:string,
    facebookId:string,
    city:string,
    country:string;
    otherDesc:string,
    userInfoMstr :{
      firstNm:string,
      fullName:string,
      email:string,
      status: any,
      userInfoMstrId: string,
      pgLocation:{
        city:string
      }
      pgUserSkillMapping:[{
        pgSkillTrackDtls:{
          pgSkillTrackMstr:{
            description:string,
            skillTrackName:string
          },
          description:string,
        },
      }]
    },
    experienceLevel:string,
    emailId:string,
    addressLine1:string,
    jobId:string,
    alternativeEmail:string,
    contactNumber:string,
    alternativeContact:string,
    governmentId:string,
  }

  assessID : any

  autoSchedule = 'changeSelectBtn'
  coachSchedule = 'secondSelectBTN'

  scheduleStatus = 'coach'

  userStatus = '';
  bsns:string;
  userDiv:boolean;
  Details=[];
  respData: any;
  candt : any
  masterSkills: any[];
  masterSkillIds= [];
  skillDetails: any[];
  assesmentDetails: any[];
  Schedules: any[];
  selectedEntry;
  mettleReport:any
  assessDiv = false;
  candiDiv = 'col-lg-6'
  closeDiv = 'col-lg-2'
lineDiv ='modal-title'
  selectedUseCase:string
  coaches = []
  eventDetails =[]
  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any
  };
  imageUrl:string = environment.imageUrl;
  constructor(protected localStorageService: LocalStorageService,
              private AuthService:AuthService,
              private router:Router,
              private route:ActivatedRoute,
              private toastr: ToastsManager,
              private navBarService: NavBarService,
              public sanitizer: DomSanitizer
             ) {

    this.assessID = 0

   // this.navBarService.setCurrentPage(2);
    this.route.params.subscribe( params =>
      this.UserID = params['id']
    )

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

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

        console.log(resp,'responseDataaaaa')
        console.log(resp.testLink,'responseDataaaaa')

        var response = resp;
        this.userStatus = resp.infoMstr.status;
        this.userData = resp.infoDetails;

        if(resp.infoDetails.pgExperienceLevel){

        }
        else {
          resp.infoDetails.pgExperienceLevel = {experienceLevel : ''}
        }


        this.candt = resp;
        this.eventDetails = resp.eventDetails;
        console.log(this.userStatus, "userStatus");
        console.log(this.userData, "userData");


        if(this.userStatus == 'TA_APPROVED'){

          this.selectedUseCase = 'primaryUseCase';
          this.assign();

        }
        else if(this.userStatus == 'METTL_APPROVED'){

          this.assign()
          this.selectedUseCase = 'technicalUseCase'
        }
        else if(this.userStatus == 'MINI_PG_COACH_APPROVED') {

          this.assign()
          this.selectedUseCase = 'bussniessUseCase'
        }
        else {
          this.selectedUseCase = 'innerUseCase'
        }

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


        if(window.location.origin == 'http://localhost:8080'){
          this.getCoachesforCandidate(1,[1,2])
        }
        else {
          this.getCoachesforCandidate(this.empData.location, this.empData.skills)
        }





        this.PGMCandidateDtls = true
        this.masterSkills = _.uniqBy(this.userData.userInfoMstr.pgUserSkillMapping, 'pgSkillTrackDtls.pgSkillTrackMstr.description');

        console.log(this.masterSkills,'masterSkills')



        this.Details=[
          {
            "info_name":"Email",
            "val":this.userData.emailId
          },
          {
            "info_name":"Phone",
            "val":this.userData.contactNumber
          },
          {
            "info_name":"Government ID",
            "val":this.userData.governmentId
          },
          {
            "info_name":"City",
            "val":this.userData.city
          },
          {
            "info_name":"Linkedin ID",
            "val":this.userData.linkedInId
          },
          {
            "info_name":"Alternate Email:",
            "val":this.userData.alternativeEmail
          },
          {
            "info_name":"Alternate Phone",
            "val":this.userData.alternativeContact
          },
          {
            "info_name":"Address",
            "val":this.userData.addressLine1
          },
          {
            "info_name":"Country",
            "val":this.userData.country
          },
          {
            "info_name":"Facebook ID",
            "val":this.userData.facebookId
          }
        ];
        this.assesmentDetails = [
          {
            "info_name":"Assessment",
            "val":this.userData.emailId
          },
          {
            "info_name":"Skill set",
            "val":this.userData.userInfoMstr.pgUserSkillMapping[0].pgSkillTrackDtls.pgSkillTrackMstr.skillTrackName
          },
          {
            "info_name":"Primary Skill",
            "val":this.userData.userInfoMstr.pgUserSkillMapping[0].pgSkillTrackDtls.pgSkillTrackMstr.skillTrackName
          },
          {
            "info_name":"User ID",
            "val":this.userData.adId
          }
        ];




        this.masterSkills.forEach(usrSkills => {
          this.masterSkillIds.push(usrSkills.pgSkillTrackDtls.pgSkillTrackMstr.skillTrackMstrId);
        });


        console.log(this.masterSkillIds,'MasterSkillIdsssss');

        this.AuthService.getAssessmentDetails(this.masterSkillIds).then(res => {
          this.respData = JSON.parse(res);

          this.Schedules = this.respData.pgAssessmentDtls;
          console.log(this.Schedules,'this.Schedules')
        }).catch(err=>{
          console.log(err)
        });


      }).catch(err => {

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


    }




  }

  ngOnInit() {
  }


  getCoachesforCandidate(Location,SkillId){
    this.coaches = []
    this.AuthService.getAllCoachesforCandidate({location:Location, skillId:SkillId}).then(responseData =>{
     console.log(responseData,'getAllCoaches')

      for(var value of responseData.userInfoDtls){
        console.log(value.userInfoMstr.fullName)
        if(value.userInfoMstr.fullName != null){
          this.coaches.push(value);
        }
      }
    }).catch(err=>{
      console.log(err)
    });
  }


  onSelectionChange(entry) {
    //noinspection TypeScriptUnresolvedFunction

    if(this.selectedUseCase == 'technicalUseCase' || this.selectedUseCase == 'bussniessUseCase'){
      this.selectedEntry = Object.assign({}, this.selectedEntry, entry);
      console.log(this.selectedEntry, 'this.selectedEntry')
    }
    else {
      this.selectedEntry = Object.assign({}, this.selectedEntry, entry);
      this.candiDiv = 'col-lg-4'
      this.closeDiv = 'col-lg-4'
      this.lineDiv = 'modal-title lineVet'
      this.assessDiv = true

      console.log(this.selectedEntry, 'this.selectedEntry')
    }
  }


  closeModal()
  {
    console.log('closeModal');
    document.getElementById('closeAssignCoachModal').click()
  }


  Initials(cString) {

    if(cString){
      return cString.replace(/\W*(\w)\w*/g, '$1').toUpperCase();
    }
    else {
      return;
    }
  }


  getSubstring(text){
    if(text) {
      return text.substring(0, 3);
    }
  }

  assign(){
    document.getElementById('openModalButton').click();
  }

 clickExpend(){

   if(this.assessDiv) {
     this.candiDiv = 'col-lg-6'
     this.closeDiv = 'col-lg-2'
     this.lineDiv ='modal-title'
     this.assessDiv = !this.assessDiv
   }
   else {
     this.candiDiv = 'col-lg-4'
     this.closeDiv = 'col-lg-4'
     this.lineDiv ='modal-title lineVet'
     this.assessDiv = !this.assessDiv
   }
  }


  goToAssessmentId(event){

    console.log(event)

    this.assessID = event
  }


   makeid() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 8; i++)
      text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
  }


  scheduleAssignCoach (coachId,EventId)
  {

    console.log(coachId,EventId)
    console.log(this.scheduleStatus )

    if(this.scheduleStatus == 'coach'){

      console.log("submitCoachtoCandidate");

      var assignReq = {

        "coachId":coachId,

        "assignCandidateRequestList":[

          {

            "userInfoMstrId":this.UserID,

            "eventDtlsId": EventId

          }
        ]

      };
      this.assignBtnEnable = true;

      this.AuthService.submitAssignCoachtoCandidate(assignReq).then(responseData =>{

        console.log(responseData,'ASSIGN COACH CANDIDATE API')

        this.toastr.success('Coach assigned successfully')
        this.selectedUseCase = 'innerUseCase';
        document.getElementById('closeAssignCoachModal').click()

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

    }
    else if(this.scheduleStatus == 'auto'){

    if( this.assessID == 0 || this.assessID == '0' ){
      this.toastr.error('Please select Assessment Details')
    }
    else {



      console.log("submitCoachtoCandidate");

      var assignReq = {

        "coachId":coachId,

        "assignCandidateRequestList":[

          {

            "userInfoMstrId":this.UserID,

            "eventDtlsId": EventId

          }
        ]

      };

      this.AuthService.submitAssignCoachtoCandidate(assignReq).then(responseData =>{

        console.log(responseData,'ASSIGN COACH CANDIDATE API')
          // var assessmenIds = Number(this.assessmentId)
          this.AuthService.scheduleCreate({assessmentId:this.assessID,name:this.makeid(),sourceApp:''}).then(res => {
            console.log(res)
            this.respData =  res
            console.log(this.respData.status)
            if(this.respData.status == 'success' || this.respData.status == 'SUCCESS'){
              this.isError = false
              this.isSuccess = true
              console.log(this.respData)
              var results = JSON.parse(this.respData.data)
              if(results.error){
                this.toastr.error("The Assessment ID is not available at this moment.")
              }
              else {
                let reg = {
                  "registrationDetails": {
                    "registrationDetails": [{
                      "uniqueId": this.makeid(),
                      "firstName": this.userData.fullName,
                      "email": this.userData.emailId
                    }]
                  },
                  "scheduleId": results.scheduleDetails.scheduleId
                }

                this.AuthService.registerUser(reg).then(res => {
                  console.log(res)
                  this.respData = res
                  console.log(this.respData.status)
                  if (this.respData.status == 'success' || this.respData.status == 'SUCCESS') {
                    this.isError = false
                    this.isSuccess = true

                    this.mettleStatus = false

                   // this.scheduleMsg = 'Schedule create successfully'
                    this.viewProfile = false
                    this.toastr.success('Mettl test scheduled Successfully');
                   // this.router.navigate(['/pgm/landing']);
                    this.userStatus = ''
                    document.getElementById('closeAssignCoachModal').click()
                    // this.router.navigate(['']);
                  }
                  else{
                    this.isError = true
                    this.isSuccess = false

                    this.errorMessage = this.respData['message']
                    setTimeout(()=>{
                      this.isError = false;
                    },6000);
                  }
                }).catch(err=>{
                  console.log(err)
                  this.isError = true
                  this.isSuccess = false
                  this.errorMessage = err['message']
                  setTimeout(()=>{
                    this.errorMessage = false;
                  },6000);
                });
                // this.router.navigate(['']);
              }
            }
            else{
              this.isError = true
              this.isSuccess = false

              this.errorMessage = this.respData['message']
              setTimeout(()=>{
                this.isError = false;
              },6000);
            }
          }).catch(err=>{
            console.log(err)
            this.isError = true
            this.isSuccess = false
            this.errorMessage = err['message']
            setTimeout(()=>{
              this.errorMessage = false;
            },6000);
          });

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



      }
    }
    else {

    }


  }


  workSpaceAssignCoach (coachId,EventId,adId){



    var assignReq = {

      "coachId":coachId,

      "assignCandidateRequestList":[

        {

          "userInfoMstrId":this.UserID,

          "eventDtlsId": EventId

        }
      ]

    };


    console.log('clicked')

    this.assignBtnEnable = true;

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

      console.log(resp,'getWorkspaceErr')

      let resPayload = resp

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



        this.AuthService.setupWorkSpace({sname:workSpaceData.adId,sbundleId:workSpaceData.bundleId,sdirId:workSpaceData.directoryId}).then(wsResp => {

          console.log(wsResp,'workSpace Response');

          if(wsResp.status == 'error') {
            this.toastr.error(wsResp.message)
          }
          else {

            console.log("AssignCoach func");
            this.AuthService.submitAssignCoachtoCandidate(assignReq).then(responseData => {

              console.log(responseData, 'ASSIGN COACH CANDIDATE API')
              this.selectedUseCase = 'innerUseCase';
              document.getElementById('closeAssignCoachModal').click()
              this.toastr.success('Coach assigned and workspace created successfully')

            }).catch(err => {
              console.log(err,'submitAssignCoachtoCandidate')
            })
          }
        }).catch(wsErr => {
          console.log(wsErr,'workSpace Error')
        })
      }

      else {
        console.log(this.respData)
      }
    }).catch(getWorkspaceErr => {
      console.log(getWorkspaceErr,'getWorkspaceErr')
    })



  }




  viewResume(profileId){

    this.AuthService.getFile(profileId).then(resp =>{

      console.log(resp.contentType)

      this.mettleReport = 'data:'+resp.contentType+';base64,'+resp.fileContent

      document.getElementById('assignModalButton').click();

    }).catch(err =>{

    })
  }

  selectSchedule(sts){

    console.log(sts)

    if(sts == 'auto'){
      this.scheduleStatus = sts;
      this.autoSchedule = 'changeSelectBtn'
      this.coachSchedule = 'secondBTN'
    }
    else if(sts == 'coach'){
      this.scheduleStatus = sts;
      this.autoSchedule = 'changeBtn'
      this.coachSchedule = 'secondSelectBTN'
    }
    else {

    }



  }


}
