import { Component, OnInit, OnDestroy, Input, Output, EventEmitter } 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 '../ta.service';
import _ from "lodash";

import { DomSanitizer, SafeResourceUrl, } from '@angular/platform-browser';
import { Utils } from 'app/utils';
import { InfoDetails } from 'app/models/candidate-dashboard-response/info-details';
import { CandidateDashboardResponse } from 'app/models/candidate-dashboard-response/candidate-dashboard-response';
import { TaModalServiceService, MODAL_CONTENT } from 'app/ta/ta-modal-service.service';
import { CANDIDATE_STATUS } from 'app/models/candidateStatus';
import { Assessment } from 'app/models/assessment/assessment.model';
import { environment } from '../../../environments/environment.dev';
@Component({
  selector: 'app-ta-profiles',
  templateUrl: './ta-profiles.component.html',
  styleUrls: ['./ta-profiles.component.css']
})
export class TaProfilesComponent implements OnInit, OnDestroy {


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


  // TODO: need to find out what is the right role
  role: String = "TA";

  modalContent: string;
  modalCandidate: string;

  private subscriptions = [];

  img_path = environment.imageUrl+'/assets/img/Taflow/';
  name: string
  fullName: string
  businessCard2: string
  viewProfile = true
  userIcon: string
  divExpand = true
  UserID: string
  dashBoards: any[];
  Schedules: any[];

  masterSkills: any[];
  masterSkillIds = [];
  skillDetails: any[];
  respData: any;
  isError = false;
  isSuccess = false;
  errorMessage: any;
  successMessage: any;
  onboardRjct: boolean
  scheduleMsg: any;
  mettleStatus: boolean;
  mettleDlsStatus: boolean;
  userData: InfoDetails;
  candidateDashboard: CandidateDashboardResponse;
  assessment: Assessment = new Assessment();

  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any,
    emailId: any;
  };
  userStatus = '';
  bsns: string;
  userDiv: boolean;
  Content = '';
  Contenttype = '';
  showCandidateDetails: boolean;
  Details = [];
  assesmentDetails = [];
  showMettle: boolean;
  mettleReport: SafeResourceUrl;
  evaluatingskill = 'Primary Skill Evaluation';
  Step1: number;
  Step2: number;
  Step3: number;

  profilePic: string;
  // Ishtiaq code
  canDetailToDisp: any;


  constructor(protected localStorageService: LocalStorageService,
    private AuthService: AuthService,
    private router: Router,
    private route: ActivatedRoute,
    private toastr: ToastsManager,
    private navBarService: NavBarService,
    public sanitizer: DomSanitizer,
    private modalService: TaModalServiceService) {

    this.navBarService.setCurrentPage(1);
    this.bsns = "50%";
    this.name = '';
    this.fullName = '';
    this.scheduleMsg = 'Schedule Assign this Candidate..'
    this.showCandidateDetails = false;
    var url_string = window.location.href;
    var url = new URL(url_string);


    //noinspection TypeScriptUnresolvedVariable
    this.UserID = url.searchParams.get("uuid")
    this.userDiv = false
    this.route.params.subscribe(params =>
      this.UserID = params['id']
    )
    console.log("this.UserID  -- ", this.UserID);
    if (!this.UserID || this.UserID == null) {
      this.router.navigate(['/ta']);
    } else {
      this.AuthService.getCandDetails(this.UserID).then(resp => {
        this.canDetailToDisp = resp;
        console.log("response", JSON.stringify(this.canDetailToDisp));
      }).catch(err => {
        console.log(err, 'error')
      })
    }

    var empData
    empData = this.localStorageService.get('userInfo');
    this.empData = empData
    console.log(this.empData, "userInfo Detailssssss")
    if (window.location.origin == 'http://localhost:8080') {
      this.name = 'sabash'
      this.fullName = 'sabash lakshmanan m'
      this.empData = {
        accessToken: '',
        loginType: '',
        fullName: 'Sabash LS',
        firstName: 'sabash',
        userInfoMstrId: 1,
        roleName: 'HEAD_COACH',
        emailId : "shuchita.rawat@altimetrik.com",
        roles: [1],
        skills: [1, 2],
        location: 1
      };
    } else {
      if (this.empData['firstName']) {
        this.name = this.empData['firstName'];
        this.fullName = this.empData['fullName'];
      }
      else {
        this.name = ''
      }
    }
  }

  ngOnInit() {
    this.navBarService.setCurrentPage(1);
  }

  ngOnDestroy() {
    this.subscriptions.forEach(sub => sub.unsubscribe());
  }

  // Initials(fullname) {
  //   return Utils.Initials(fullname);
  // }

  // getTrim(text) {
  //   return text.substring(6);
  // }

  // gotoTaDashboard(id) {
  //   window.location.href = window.location.origin + '/ta?' + 'uuid=' + id
  // }

  // showCandidateInfo() {
  //   this.showCandidateDetails = true;
  // }

  // expandUserInfo() {
  //   this.viewProfile = false
  //   this.businessCard2 = '308%'
  //   this.bsns = '30%';
  //   this.divExpand = false
  //   this.mettleStatus = true
  // }

  // expandUserInfo1() {
  //   this.viewProfile = true
  //   this.businessCard2 = '100%'
  //   this.bsns = '50%'
  //   this.divExpand = true
  //   if (this.userData.userInfoMstr.status == 'ONBOARDED' || this.userData.userInfoMstr.status == 'TA_APPROVED') {

  //     this.mettleStatus = true
  //   } else {
  //     this.mettleStatus = false
  //   }

  // }

  // scheduleTest() {

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

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

  //     return text;
  //   }

  //   this.isError = false;

  //   if (this.assessmentId == null || this.assessmentId == "" || this.assessmentId == undefined) {
  //     this.isError = true;
  //     this.errorMessage = "Please enter a valid assessmentId.";
  //   }

  //   if (!this.isError) {

  //     // var assessmenIds = Number(this.assessmentId)
  //     this.AuthService.scheduleCreate({ assessmentId: this.assessmentId, name: 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": 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.toastr.success('Mettl test scheduled Successfully');
  //               this.router.navigate(['/ta']);

  //               // 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);
  //     });
  //   }
  // }

  // taEdit(id) {
  //   window.location.href = window.location.origin + '/taEditProfile?' + 'uuid=' + id
  // }

  // getResultMettle(emailId) {
  //   this.AuthService.getCandidatePrimaryEvaluationReport({ email: this.userData.emailId }).then(responseData => {
  //     var report = responseData
  //     this.mettleReport = this.sanitizer.bypassSecurityTrustResourceUrl(report.candidate.testStatus.pdfReport);
  //     this.showMettle = true;
  //   }).catch(err => {
  //     this.showMettle = false;
  //     this.toastr.error("Report is not available yet");
  //     console.log(err)
  //   });
  // }

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

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

  // leaveLogout(eventObject) {
  //   this.userIcon = '';
  // }

  // logout() {
  //   console.log("logout");
  //   this.localStorageService.clearAll();
  //   localStorage.clear();
  //   this.router.navigate(['']);
  // }

  // getFiles(id) {
  //   this.AuthService.getFile(id).then(resp => {
  //     console.log(resp, 'getAllFileDetasilssss');
  //     var saveByteArray = (function () {
  //       var a = document.createElement("a");
  //       document.body.appendChild(a);
  //       // a.style = "display: none";
  //       return function (data, name) {
  //         var blob = new Blob(data, { type: "octet/stream" }),
  //           url = window.URL.createObjectURL(blob);
  //         a.href = url;
  //         a.download = name;
  //         a.click();
  //         window.URL.revokeObjectURL(url);
  //       };
  //     }());

  //     var sampleBytes = this.base64ToArrayBuffer(resp.fileContent);
  //     saveByteArray([sampleBytes], resp.fileName);

  //   }).catch(err => {
  //   })
  // }

  // viewResume() {
  //   this.AuthService.getFile(this.userData.profileId).then(resp => {
  //     this.mettleReport = 'data:' + resp.contentType + ';base64,' + resp.fileContent;
  //   }).catch(err => {

  //   })
  // }

  // base64ToArrayBuffer(base64) {
  //   var binaryString = window.atob(base64);
  //   var binaryLen = binaryString.length;
  //   var bytes = new Uint8Array(binaryLen);
  //   for (var i = 0; i < binaryLen; i++) {
  //     var ascii = binaryString.charCodeAt(i);
  //     bytes[i] = ascii;
  //   }
  //   return bytes;
  // }

  // selectedEvaluation(evaluationskill, step) {
  //   if (step == 1) {
  //     this.evaluatingskill = evaluationskill;
  //     this.Step1 = 1;
  //   }
  //   else if (step == 2) {
  //     this.evaluatingskill = evaluationskill;
  //     this.Step2 = 2;
  //   }
  //   else {
  //     this.evaluatingskill = evaluationskill;
  //     this.Step3 = 3;
  //   }
  // }

  // get showExtendedDetails() {
  //   return /^(TA_APPROVED|TA_REJECTED|ONBOARDED)$/.test(this.candidateDashboard.infoMstr.status);
  // }

}

// export class TaProfilesComponent implements OnInit {
  
//   constructor(){
//     this.route.params.subscribe(params =>
//       //       this.UserID = params['id']
//       //     )
//   }
//   ngOnInit() {
//   }

// }