import { Component, Input, ViewChild, OnInit } from '@angular/core';
import { FormControl, Validators, FormGroup } from '@angular/forms';
import { AuthService } from 'app/services/auth.service';
import { Router } from '@angular/router';
import { LocalStorageService } from 'angular-2-local-storage';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { NavBarService } from '../ta.service';

import { StepperSelectionEvent } from '@angular/cdk/stepper';
import { STEP_STATUS, Candidate } from './ta-add-profile.component'
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Utils } from 'app/utils';
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,}))$/;

@Component({
  selector: 'app-ta-edit-profile',
  templateUrl: './ta-add-profile.component.html',
  styleUrls: ['./ta-add-profile.component.scss']
})

export class TaEditProfileComponent implements OnInit {

  title = "Edit Candidate";

  candidate: Candidate = {} as Candidate;

  userProfilePic: SafeUrl;

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

  firstName: string = '';
  lastName: string = '';
  email: string = '';
  contact: string = '';
  jobId: string = '';
  location: string = '';
  govtId: string = '';
  altrEmail: string = '';
  address: string = '';
  city: string = '';
  altrContact: string = '';
  faceBookId: string = '';
  twitterId: string = '';
  linkedInId: string = '';

  experience: string = '';
  primarySkill: any = [];
  secondarySkill: string = '';
  other: string = '';
  resume: string = '';
  selectedValue: string = '';
  link: string = '';

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

  isError = false;
  isSuccess = false;
  errorMessage: any;
  successMessage: any;

  uploadFileName = '';

  userIcon: string;
  name: string
  Error: string
  fullName: string
  public exps
  userData: {
    userInfoDtlsId: string,
    userInfoMstrId: string,
    adId: string,
    profileName: string,
    profileId: string,
    firstName: string,
    lastName: string,
    fullName: string,
    country: string,
    city: string,
    email: string,
    location: string,
    addressLine1: string,
    facebookId: string,
    linkedInId: string,
    twitter: string,
    googleId: string,
    pgExperienceLevel: {
      experienceLevelId: string
    },
    pgSkillTrackDtls: {
      pgSkillTrackMstr: {
        description: string
      },
      description: string,
    },
    userInfoMstr: {
      status: any,
      userInfoMstrId: string,
      pgLocation: any,
      pgUserFileMapping: any
    },

    experienceInYrs: string,
    experienceLevel: string,
    emailId: string,
    jobId: string,
    status: any,
    alternativeEmail: string,
    contactNumber: string,
    alternativeContact: string,
    governmentId: string,
    otherDesc: string,
  }

  myFile: File;
  profilePic: File;
  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any
  };
  Skills: any[]
  userinfo_mstr;
  locations;

  Indicators = [
    {
      "step": "Basic Details",
      "status": STEP_STATUS.IN_PROGRESS
    },
    {
      "step": "Contact Details",
      "status": STEP_STATUS.NOT_STARTED
    },
    {
      "step": "Resume",
      "status": STEP_STATUS.NOT_STARTED
    }
  ];

  UserID: string
  CandidateData: boolean

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

  // expLevels = [{ id:1,value:'BEGINNER'},{ id:2,value:'INTERMEDIATE'},{ id:3,value:'ADVANCED'}]
  expLevels;
  experienceLevel;
  constructor(
    protected localStorageService: LocalStorageService,
    private AuthService: AuthService,
    private router: Router,
    private toastr: ToastsManager,
    private navBarService: NavBarService,
    private sanitizer: DomSanitizer
  ) {

    // TODO: add validations for the profile picture
    this.formGroup1 = new FormGroup({
      firstName: new FormControl('', Validators.required),
      lastName: new FormControl('', Validators.required),
      jobId: new FormControl('', Validators.required),
      location: new FormControl('', Validators.required),
      experience: new FormControl('', Validators.required),
      primarySkill: new FormControl('', Validators.required)
    });

    this.formGroup2 = new FormGroup({
      contact: 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.CandidateData = false
    this.userIcon = '';

    this.name = '';
    this.fullName = ''

    //noinspection TypeScriptUnresolvedFunction
    var searchParams = new URLSearchParams(window.location.search); //?anything=123
    this.UserID = searchParams.get("uuid")


    if (!this.UserID) {
      this.router.navigate(['ta']);
    } else {

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

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

        var datas = resp.eventDetails

        if (resp.status == 'error') {
          this.router.navigate(['ta']);
        }

        var skillset = []

        this.userData = resp.infoDetails;
        this.experienceLevel = resp.infoDetails.pgExperienceLevel;
        this.userinfo_mstr = resp.infoMstr;

        this.userData.firstName = resp.infoMstr.firstNm;
        this.userData.lastName = resp.infoMstr.lastNm;

        this.CandidateData = true

        resp.infoMstr.pgUserSkillMapping.forEach(skills => {

          skillset.push(skills.pgSkillTrackDtls.skillTrackDtlsId)

        })

        console.log(skillset, 'skill Set')

        if (this.userData) {
          // TODO: clean up this
          this.candidate.firstName = this.firstName = this.userData.firstName
          this.candidate.lastName = this.lastName = this.userData.lastName
          this.candidate.email = this.email = this.userData.emailId
          this.candidate.contactNumber = this.contact = this.userData.contactNumber
          this.candidate.jobTitle = this.jobId = this.userData.jobId
          this.candidate.location = this.location = this.userData.userInfoMstr.pgLocation.locationId
          this.candidate.locationId = this.userData.userInfoMstr.pgLocation.locationId
          // this.govtId = this.userData.governmentId
          this.candidate.alternativeEmail = this.altrEmail = this.userData.alternativeEmail
          this.candidate.addressLine1 = this.address = this.userData.addressLine1
          // this.candidate.addressLine2 = this.address = this.userData.addressLine2
          this.candidate.city = this.city = this.userData.city
          this.candidate.country = this.userData.country
          this.candidate.alternativeContact = this.altrContact = this.userData.alternativeContact
          this.candidate.facebookId = this.faceBookId = this.userData.facebookId
          this.candidate.twitter = this.twitterId = this.userData.twitter
          this.candidate.linkedInId = this.linkedInId = this.userData.linkedInId

          this.candidate.experienceLevel = this.experience = this.experienceLevel.experienceLevelId;
          this.candidate.experienceId = this.experienceLevel.experienceLevelId;
          console.log('experience', this.experience);

          this.candidate.skillId = this.primarySkill = skillset;
          this.candidate.profileName = this.uploadFileName = this.userData.profileName;
          this.profileName = this.userData.profileName;
          this.profileId = this.userData.profileId;
          this.candidate.profileId = parseInt(this.userData.profileId, 10);
          this.candidate.otherDesc = this.other = this.userData.otherDesc;

          let profilePicInfo = this.userData.userInfoMstr.pgUserFileMapping.find(i => { return i.fileType === 'PROFILEIMAGE' });

          if (profilePicInfo) {
            this.AuthService.getFile(profilePicInfo.fileId).then(resp => {
              this.userProfilePic = this.sanitizer.bypassSecurityTrustUrl(Utils.fileToDataURL(resp[0]));

              this.candidate.profilePicFileName = profilePicInfo.fileName;
              this.candidate.profilePicId = resp[0].contentType
            });
          }

        }
        console.log(this.userData, "this.userData");
        //console.log(this.userData.pgExperienceLevel.experienceLevel);
      }).catch(err => {
        console.log(err, 'error');

      })
    }

    this.empData = this.localStorageService.get('userInfo');

    if (window.location.origin == 'http://localhost:8080') {
      this.empData = {
        accessToken: '',
        loginType: '',
        fullName: 'Sabash LS',
        firstName: 'sabash',
        userInfoMstrId: 9,
        roleName: 'HEAD_COACH',
        roles: [1],
        skills: [1, 2],
        location: 1
      };
    }

    if (this.empData['firstName']) {
      this.name = this.empData['firstName'];
      this.fullName = this.empData['firstName'];
    } else {
      this.name = ''
      this.fullName = ''
    }

    this.AuthService.getAllSkill().then(res => {
      var skill = res;
      console.log(skill, "Skills")
      this.Skills = skill.pgSkillTrackDtlsList

      console.log(this.Skills, "skills")
    }).catch(err => {
      console.log(err)
    });

    this.AuthService.getLocations().then(res => {
      var skill = res;
      this.locations = skill.pgLocationList
      console.log(this.locations, "locations")
    }).catch(err => {
      console.log(err)
    });

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

  }

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

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

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

  fileChange(files) {
    console.log(files);
    var 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...";
    }

  }

  uploadSumbit() {
    if (this.myFile == null || this.myFile == undefined || !this.myFile) {
      if (this.profilePic) {
        this.uploadProfilePic();
      } else {
        this.update();
      }
    } else {

      let formData: any = new FormData();

      formData.append("file", this.myFile, this.uploadFileName);

      this.AuthService.getEditResumeUpload(formData, this.userData.userInfoMstr.userInfoMstrId).then(resp => {
        this.profileId = resp.fileId
        this.profileName = this.uploadFileName

        if (this.profilePic) {
          this.uploadProfilePic();
        } else {
          this.update();
        }

      }).catch(err => {

      });
    }
  }

  uploadProfilePic() {
    let profilePicForm = new FormData();
    profilePicForm.append("file", this.profilePic, this.profilePic.name);

    this.AuthService.getEditResumeUpload(profilePicForm, this.userData.userInfoMstr.userInfoMstrId).then(res => {

      this.profilePicId = res.fileId;
      this.profilePicName = this.profilePic.name;

      this.update();

    }).catch(err => {
      console.log('error while uploading the profile picture')
    });
  }

  update() {
    console.log(this.profileId, 'registerr data', this.userData.userInfoDtlsId)

    // edit Only changes
    this.candidate.userInfoDtlsId = this.userData.userInfoDtlsId;
    this.candidate.userInfoMstrId = this.userData.userInfoMstr.userInfoMstrId;

    // 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.candidateUpdate(this.candidate).then(response => {

      // if we have a profile pic link it as a profile pic
      // if (this.profilePic) {
      //   this.AuthService.candidateMapProfilePic(response.data.pgUserInfoMstr.userInfoMstrId, this.candidate.profilePicId, this.candidate.profilePicFileName).then(r => {
      //     this.finishFlow(response);
      //   });
      // } else {
      this.finishFlow(response);
      // }
    }).catch(err => {
      console.log('update', err);
      this.isError = true;
      this.isSuccess = false;
      this.errorMessage = err['message'];
    });
  }

  finishFlow(response) {
    console.log('finish flow', response);
    if (response.status == 'success') {
      this.isError = false;
      this.isSuccess = true;
      this.toastr.success('The candidate details were successfully updated.');
      this.router.navigate(['/ta']);
    } else {
      this.isError = true;
      this.isSuccess = false;
      this.errorMessage = response['message'];
    }
  }

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

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

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

    fr.readAsDataURL(this.profilePic);
  }
}
