import { UserInfo } from './../../models/userInfo.model';
import { UserInfoMstr } from './../../models/user/user.model';
import { Component, Input, ViewChild, OnInit, NgModule, Output, EventEmitter } from '@angular/core';
import { FormControl, Validators, FormGroup, FormBuilder } from '@angular/forms';
import { AuthService } from 'app/services/auth.service';
import { TaHttpService } from 'app/services/ta/ta-http.service';
import { Router } from '@angular/router';
import { LocalStorageService } from 'angular-2-local-storage';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { StepperSelectionEvent } from '@angular/cdk/stepper';
import { NavBarService } from '../ta.service';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { environment } from '../../../environments/environment.dev';

const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

export interface Candidate {
  userInfoDtlsId: any;
  userInfoMstrId: any;
  firstName: string;
  lastName: string;
  adId: string;   // email
  email: string;  // email
  contactNumber: string,
  jobTitle: string, // this.jobId,
  location: number, // this.location,
  locationId: number, // this.location,
  governmentId: string, // this.govtId,
  alternativeEmail: string, // this.altrEmail,
  addressLine1: string, // this.address,
  addressLine2: string, // this.address,
  city: string, // this.city,
  country: string, // this.city,
  alternativeContact: string, // this.altrContact,
  facebookId: string, // this.faceBookId,
  twitter: string, // this.faceBookId,
  googleId: string, // this.twitterId,
  linkedInId: string, // this.linkedInId,
  experienceLevel: number, // this.experience,
  experienceId: number, // this.experience,
  skillId: number[], // this.primarySkill,
  // secondarySkill: this.secondarySkill,
  otherDesc: string, // this.other,
  resume: string, // this.resume,
  profileId: number, // this.profileId,
  profileName: string, // this.profileName,
  profilePicId: number,
  profilePicFileName: string,
  taId: number // this.empData.userInfoMstrId
}

export enum STEP_STATUS {
  COMPLETED = 'completed',
  IN_PROGRESS = 'inProgress',
  NOT_STARTED = 'notStarted'
}

@Component({
  selector: 'app-ta-add-candidate',
  templateUrl: './ta-add-candidate.component.html',
  styleUrls: ['./ta-add-candidate.component.scss'],
  providers: [TaHttpService]
})
export class TaAddCandidateComponent implements OnInit {

  title = 'Add Candidate';

  @Input()
  candidate: Candidate = {} as Candidate;

  formGroup1: FormGroup;
  formGroup2: FormGroup;
  formGroup4: FormGroup;

  userProfilePic: SafeUrl;

  @Input() firstName = '';
  @Input() lastName= '';
  @Input() email= '';
  @Input() contact = '';
  @Input() jobId = '';
  @Input() location = '';
  @Input() govtId = '';
  @Input() altrEmail = '';
  @Input() address = '';
  @Input() city = '';
  @Input() altrContact = '';
  @Input() faceBookId = '';
  @Input() twitterId = '';
  @Input() linkedInId = '';

  @Input() experience = '';
  @Input() primarySkill: any;
  @Input() secondarySkill = '';
  @Input() other = '';
  @Input() resume = '';
  @Input() selectedValue = '';
  @Input() link = '';

  // @Input() editCandInfo:any;
  @Input()  set editCandInfo(role) { this.candidateToEdit = role; this.status = status }
  candidateToEdit: any;
  status:any;
  isEditCand: boolean = false;
  @Output() editCandSucc = new EventEmitter<boolean>();

  profileId: any;
  profileName: any;
  profilePicId: any;
  profilePicName: any;


  form1val = false;
  form2val = false;
  form3val = false;

  isError = false;
  isSuccess = false;
  errorMessage: any;
  successMessage: any;
  uploadFileName = '';
  Error: string;
  step1Form: boolean;
  step2Form: boolean;
  step3Form: boolean;
  step4Form: boolean;
  titleClass1: any;
  titleClass2: any;
  titleClass3: any;
  titleClass4: any;
  userIcon: string;
  name: string;
  fullName: string;
  isApprove: boolean;
  public exps;
  respData: any;
  experiences: any[];
  Skills: any[];
  jobDetails: any[];
  locations: any[];
  myFile: File;
  profilePic: File;
  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any,
    emailId: any
  };
  resumeId: number;
  candResume: any;

  expLevels = [{ id: 1, value: 'BEGINNER' }, { id: 2, value: 'INTERMEDIATE' }, { id: 3, value: 'ADVANCED' }]

  Indicators = [
    {
      'step': 'Candidate Details',
      'status': STEP_STATUS.IN_PROGRESS
    },
    {
      'step': 'Resume',
      'status': STEP_STATUS.NOT_STARTED
    }
  ];

  Act = 'basicDetails';
  @ViewChild('fileInput') fileInput;

  img_path = environment.imageUrl+'/assets/img/Taflow/';

  constructor(
    protected localStorageService: LocalStorageService,
    private AuthService: AuthService,
    private router: Router,
    private toastr: ToastsManager,
    private navBarService: NavBarService,
    private taService: TaHttpService,
    private sanitizer: DomSanitizer,
    private fb: FormBuilder
  ) {

    // TODO: add validations for the profile picture
    this.formGroup1 = new FormGroup({
      firstName: new FormControl('', [Validators.required, Validators.pattern('^[a-zA-Z ]*$')]),
      lastName: new FormControl('', [Validators.required, Validators.pattern('^[a-zA-Z ]*$')]),
      emailId: new FormControl('', [Validators.required, Validators.email]),
      contactNumber: new FormControl('', Validators.required),
      jobId: new FormControl('', Validators.required),
      locationId: new FormControl('', Validators.required),
      experienceId: new FormControl('', Validators.required),
      skillIds: new FormControl('', Validators.required)
    });

    this.formGroup2 = new FormGroup({
      contactNumber: new FormControl('', Validators.required),
      altrContact: new FormControl(''),
      email: new FormControl('', [Validators.required, Validators.email]),
      altrEmail: new FormControl(''), // angular bug email validator does not support null or empty values
      address: new FormControl('', Validators.required),
      address2: new FormControl(''),
      city: new FormControl('', Validators.required),
      country: new FormControl('', Validators.required),
      linkedInId: new FormControl(''),
      twitterId: new FormControl(''),
      facebookId: new FormControl(''),
    });
    this.formGroup4 = new FormGroup({
      file: new FormControl(''), // not using required since its controlled manually
      link: new FormControl('')
    });

    this.userIcon = '';
    this.step1Form = true;
    this.step2Form = false;
    this.step3Form = false;
    this.step4Form = false;
    this.isError = false;

    this.name = '';
    this.fullName = '';
    let empData;
    empData = this.localStorageService.get('userInfo');
    this.empData = empData;

    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: 9,
        roleName: 'HEAD_COACH',
        roles: [1],
        skills: [1, 2],
        location: 1,
        emailId: 'gananthakrishnan@altimetrik.com'
      };
    } else {
      if (this.empData['firstName']) {
        this.name = this.empData['firstName'];
        this.fullName = this.empData['fullName'];
        this.email = this.empData['email'];
      } else {
        this.name = '';
        this.fullName = '';
      }
    }

    this.AuthService.getAllSkill().then(res => {
      const skill = res;
      console.log(skill, 'Skills');
      this.Skills = skill.pgSkillTrackDtlsList;
      console.log(this.Skills, 'skills');
    }).catch(err => {
      console.log(err);
    });

    this.taService.getJobTitle().subscribe(data => {
      this.jobDetails = data;
    }, err => {
      console.log(err);
    });
    this.AuthService.getLocations().then(res => {
      const skill = res;
      this.locations = skill.pgLocationList;
      console.log(this.locations, 'locations');
    }).catch(err => {
      console.log(err);
    });

    this.AuthService.getAllExperienceLevel().then(res => {
      const exp = res;
      this.expLevels = exp.pgExperienceList;
      console.log(this.expLevels, 'getAllExperience');
    }).catch(err => {
      console.log(err);
    });
  }

  ngOnInit() {
    this.navBarService.setCurrentPage(2);
    console.log("on init cand edit inort --- ",this.candidateToEdit);
    if(this.candidateToEdit){
      this.candidate.skillId = [];
      this.candidateToEdit.candInfoDts.userInfoMstr.pgUserSkillMapping.forEach(element => {
        this.candidate.skillId.push(element.pgSkillTrackDtls.skillTrackDtlsId);
      });
      this.formGroup1.setValue({firstName : this.candidateToEdit.candInfoDts.userInfoMstr.firstName, lastName: this.candidateToEdit.candInfoDts.userInfoMstr.lastName, emailId: this.candidateToEdit.candInfoDts.userInfoMstr.emailId, locationId: this.candidateToEdit.candInfoDts.userInfoMstr.pgLocation.locationId, contactNumber: this.candidateToEdit.candInfoDts.userInfoMstr.mobileNo, skillIds: this.candidate.skillId, jobId: this.candidateToEdit.candInfoDts.jobId, experienceId: this.candidateToEdit.candInfoDts.pgExperienceLevelId});
      this.candidate.experienceLevel = this.candidateToEdit.candInfoDts.pgExperienceLevelId;
      this.isEditCand = true;
      this.candidateToEdit.candInfoDts.userInfoMstr.pgUserFileMapping.forEach(element => {
        if(element.fileType === 'RESUME'){
          this.resumeId = element.fileId;
          this.uploadFileName = element.fileName;
          // return false;
        }
        if(element.fileType === 'PROFILEIMAGE'){
          this.profileId = element.fileId;
          this.profilePicName = element.fileName;
          // return false;
        }
      });
      this.downloadCandResume(this.resumeId);
      if(this.candidateToEdit.status){
        console.log(this.candidateToEdit.status);
        if(this.candidateToEdit.status !== 'ONBOARDED'){
          this.formGroup1.get('emailId').disable();
        }
      }
    }
   
  }

  downloadCandResume(id){
    console.log("candidate resume file id -- ", id);
    this.AuthService.getFile(id).then(res =>{
      // this.resFile = res[0].fileName;
      // this.contType = res[0].contentType;
      this.candResume = res[0].fileContent;
      this.formGroup4.patchValue({file:this.candResume, link:null});
      // this.downlaodFile(this.resFile, this.contType, this.candResume);
    })
  }

  clearError(validation) {
    this.Error = '';
  }

  stepF1() {
    this.Act = 'basicDetails';
    this.isError = false;
    this.isSuccess = false;

    this.step1Form = true;
    this.step2Form = false;
    this.step3Form = false;
    this.step4Form = false;

  }
  stepF2() {
    if (this.form1val) {
      this.Act = 'contactDetails';
      this.isError = false;
      this.isSuccess = false;

      this.step1Form = false;
      this.step2Form = true;
      this.step3Form = false;
      this.step4Form = false;
    }
  }
  stepF3() {
    if (this.form2val) {
      this.Act = 'skillDetails';
      this.isError = false;
      this.isSuccess = false;

      this.step1Form = false;
      this.step2Form = false;
      this.step4Form = false;
      this.step3Form = true;
    }
  }
  stepF4() {
    if (this.form3val) {
      this.Act = 'resume';
      this.isError = false;
      this.isSuccess = false;

      this.step4Form = true;
      this.step2Form = false;
      this.step3Form = false;
      this.step1Form = false;
    }
  }

  form1Submit() {
    const re = /^(([^<>()\[\]\\.,;:\s@']+(\.[^<>()\[\]\\.,;:\s@']+)*)|('.+'))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    const mobile = /^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?[0123456789]\d{9}$/;

    this.isError = false;
    this.isSuccess = false;

    if (this.email == null || this.email === '' || this.email === undefined || !re.test(this.email)) {
      this.isError = true;
      this.Error = 'email';
      this.errorMessage = 'please enter a valid email.';
    }

    if (this.govtId == null || this.govtId === '' || this.govtId === undefined) {
      this.isError = true;
      this.Error = 'govtId';
      this.errorMessage = 'please enter a valid government Id.';
    }
    if (this.contact == null || this.contact === '' || this.contact === undefined || !mobile.test(this.contact)) {
      this.isError = true;
      this.Error = 'contact';
      this.errorMessage = 'please enter a valid contact.';
    }
    if (this.location == null || this.location === '' || this.location === undefined) {
      this.isError = true;
      this.Error = 'location';
      this.errorMessage = 'please enter a valid location.';
    }
    if (this.jobId == null || this.jobId === '' || this.jobId === undefined) {
      this.isError = true;
      this.Error = 'jobId';
      this.errorMessage = 'please enter a valid jobTitle.';
    }
    if (this.lastName == null || this.lastName === '' || this.lastName === undefined) {
      this.isError = true;
      this.Error = 'lastName';
      this.errorMessage = 'please enter a valid last name.';
    }
    if (this.firstName == null || this.firstName === '' || this.firstName === undefined) {
      this.isError = true;
      this.Error = 'firstName';
      this.errorMessage = 'please enter a valid first name.';
    }

    if (!this.isError) {

      this.step1Form = false;
      this.step2Form = true;
      this.step3Form = false;
      this.step4Form = false;
      this.Act = 'contactDetails';
      this.form1val = true;
    }
  }

  form2Submit() {
    const re = /^(([^<>()\[\]\\.,;:\s@']+(\.[^<>()\[\]\\.,;:\s@']+)*)|('.+'))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    const mobile = /^(?:(?:\+|0{0,2})91(\s*[\-]\s*)?|[0]?)?\d{9}$/;
    // call AuthService function here...!

    this.isError = false;
    this.isSuccess = false;

    if (this.city == null || this.city === '' || this.city === undefined) {
      this.isError = true;
      this.Error = 'city';
      this.errorMessage = 'Please enter a valid city.';
    }
    if (this.address == null || this.address === '' || this.address === undefined) {
      this.isError = true;
      this.Error = 'address';
      this.errorMessage = 'Please enter a valid address.';
    }

    if (!this.isError) {

      this.step1Form = false;
      this.step3Form = true;
      this.step2Form = false;
      this.step4Form = false;
      this.Act = 'skillDetails';
      this.form2val = true;
    }
  }

  form3Submit() {
    console.log(this.primarySkill);
    // call AuthService function here...!
    this.isError = false;
    this.isSuccess = false;

    if (this.primarySkill == null || this.primarySkill === '' || this.primarySkill === undefined) {
      this.isError = true;
      this.Error = 'primarySkill';
      this.errorMessage = 'Please enter a valid Primary Skill.';
    }
    if (this.experience == null || this.experience === '' || this.experience === undefined) {
      this.isError = true;
      this.Error = 'ExperienceLevel';
      this.errorMessage = 'Please enter a valid Experience level.';
    }

    if (!this.isError) {
      this.step1Form = false;
      this.step4Form = true;
      this.step2Form = false;
      this.step3Form = false;
      this.Act = 'resume';
      this.form3val = true;
    }
  }

  setProfilePic(files) {
    this.profilePic = files[0];

    const fr = new FileReader();
    fr.onload = () => {
      this.userProfilePic = this.sanitizer.bypassSecurityTrustUrl(fr.result);
    };

    fr.readAsDataURL(this.profilePic);
  }

  fileChange(files) {
    console.log(files);
    const file = files[0];
    this.isError = false;
    this.myFile = file;

    if (file.size <= 5e+6) {
      this.uploadFileName = file.name;
    } else {
      this.isError = true;
      this.errorMessage = 'File size is exceeded...';
    }
  }

  addCandidate() {
    const candidateDetails = {
      loggedInUser:  this.email,
      jobId: this.formGroup1.value.jobId,
      firstName: this.formGroup1.value.firstName,
      lastName: this.formGroup1.value.lastName,
      emailId: this.formGroup1.value.emailId,
      locationId: this.formGroup1.value.locationId,
      contactNumber: this.formGroup1.value.contactNumber,
      skillIds: this.formGroup1.value.skillIds,
      experienceId: this.formGroup1.value.experienceId,
      profileId: this.profileId,
      profileName: this.profileName,
      taId: this.empData.userInfoMstrId,
    };
    if (this.profilePicId) {
      candidateDetails['profilePicId'] = this.profilePicId;
      candidateDetails['profilePicFileName'] = this.profilePicName;
    }
    this.taService.addCandidate(candidateDetails).subscribe(resp => {
      this.finishFlow(resp);
    }, err => {
      this.finishFlow(err.error.errorBean);
    });
  }

  editCandidateDtls(){
    if(!this.empData.emailId){
      this.empData.emailId = this.email;
    }
    if(!this.formGroup1.value.emailId){
      this.formGroup1.value.emailId = this.candidateToEdit.candInfoDts.userInfoMstr.emailId;
    }
    const candidateDetails = {
      userInfoMstrId: this.candidateToEdit.candInfoDts.userInfoMstr.userInfoMstrId,
      loggedInUser: this.empData.emailId,
      jobId: this.formGroup1.value.jobId,
      firstName: this.formGroup1.value.firstName,
      lastName: this.formGroup1.value.lastName,
      emailId: this.formGroup1.value.emailId,
      locationId: this.formGroup1.value.locationId,
      contactNumber: this.formGroup1.value.contactNumber,
      skillIds: this.formGroup1.value.skillIds,
      experienceId: this.formGroup1.value.experienceId,
      profileId: this.profileId,
      profileName: this.profileName,
      taId: this.empData.userInfoMstrId,
      
    };
    if (this.profilePicId) {
      candidateDetails['profilePicId'] = this.profilePicId;
      candidateDetails['profilePicFileName'] = this.profilePicName;
    }
    console.log('edit cand details --- ',candidateDetails);
    this.taService.editCandidate(candidateDetails).subscribe(resp => {
      this.finishFlow(resp);
    }, err => {
      this.finishFlow(err.error.errorBean);
    });
  }

  uploadSumbit() {
    this.isError = false;
    if ((this.myFile == null || this.myFile === undefined || !this.myFile) && !this.isEditCand) {
      this.isError = true;
      this.errorMessage = 'Please upload a resume file.';
      this.toastr.error('Please upload a resume file.');
      console.log('missing file');
    }
    if (!this.isError) {
      console.log('formGroup1', this.formGroup1);
      const profilePicForm = new FormData();
      // upload profile picture , if profile picture added
      if (this.profilePic) {
        profilePicForm.append('file', this.profilePic, this.profilePic.name);
        // getResumeUpload is the common api to upload files not just for resumes
        this.AuthService.getFileUpload(profilePicForm).then(res => {

        this.profilePicId = res.fileId;
        this.profilePicName = res.fileName;

      }).catch(err => {
        console.log('error while uploading the profile picture');
      });
    }
    // Upload candidate prifile
      if (this.myFile) {
          const formData: any = new FormData();
           formData.append('file', this.myFile, this.uploadFileName);
          // getResumeUpload is the common api to upload files not just for resumes
          this.AuthService.getFileUpload(formData).then(res => {
            this.profileId = res.fileId;
            this.profileName = res.fileName;
            if(this.isEditCand){
              this.editCandidateDtls()
            }
            else{
            this.addCandidate();
            }
          }).catch(err => {
            console.log('error while uploading the profile picture');
          });
        }
        else if(this.isEditCand){
          this.editCandidateDtls();
        }
  }
}

// commentted, Since we are not using this method
/**  register() {

    this.isError = false;
    this.isSuccess = false;

    if (!this.isError) {

      // save CV details on candidate
      this.candidate.profileId = this.profileId;
      this.candidate.profileName = this.profileName;

      // relate profile pic with the candidate
      this.candidate.profilePicFileName = this.profilePicName;
      this.candidate.profilePicId = this.profilePicId;

      // fields with duplicated values
      this.candidate.taId = this.empData.userInfoMstrId;
      this.candidate.adId = this.candidate.email;
      this.candidate.locationId = this.candidate.location;
      this.candidate.experienceId = this.candidate.experienceLevel;

      this.AuthService.candidateRegister(this.candidate).then(response => {

        // if we have a profile pic link it as a profile pic
        // if (this.candidate.profilePicId) {
        //   this.AuthService.candidateMapProfilePic(response.data.pgUserInfoDtls.userInfoMstr.userInfoMstrId, this.candidate.profilePicId, this.candidate.profilePicFileName).then(r => {
        //     this.finishFlow(response);
        //   });
        // } else {
        this.finishFlow(response);
        // }

      }).catch(err => {
        this.isError = true;
        this.isSuccess = false;
        this.errorMessage = err['message'];
        this.toastr.error = this.errorMessage;
      });
    }
  } **/

  private finishFlow(response) {
    if (response.successMessage) {
      this.candidate = {} as Candidate;
      this.isError = false;
      this.isSuccess = true;
      if(this.isEditCand){
        this.toastr.success('Candidate Details Updated successfully');
        this.editCandSucc.emit(true);
      }
      else{
        this.toastr.success('Aspirant On boarded successfully');
        this.router.navigate(['/ta']);
      }
    }else if (response.errorMessage) {
      console.log(response.errorMessage);
      this.toastr.error(response.errorMessage);
      this.isError = true;
      this.isSuccess = false;
      this.errorMessage = response.errorMessage;
    }else {
      console.log(response['message']);
      this.toastr.error(response['message']);
      this.isError = true;
      this.isSuccess = false;
      this.errorMessage = response['message'];
      // this.toastr.error = this.errorMessage;
    }
  }

  callMe() {
    this.userIcon = 'logout';
  }

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

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

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

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


  /**
   * Update the indicators on the top when the stepper selected
   * step changes.
   * @param event StepperSelectionEvent
   */
  stepperChange(event: StepperSelectionEvent) {
    this.Indicators = this.Indicators.map((item, index) => {
      return {
        ...item,
        'status': this.stepStatus(index, event.selectedIndex)
      }
    })
  }
  /**
   * Get the right status based on the indicator index and
   * selected step
   * @param stepIndex indicator index
   * @param currentStep current selected step
   */
  private stepStatus(stepIndex, currentStep) {
    if (currentStep === stepIndex) {
      return STEP_STATUS.IN_PROGRESS;
    } else if (currentStep > stepIndex) {
      return STEP_STATUS.COMPLETED;
    } else {
      return STEP_STATUS.NOT_STARTED;
    }
  }
}
