import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { Router, ActivatedRoute, RouterModule } from '@angular/router';
import { Title } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { Resume, ResumeCertification, ResumeEducation, ResumeExperience, ResumeExperienceBullet, ResumeLanguage, ResumeMilitary, ResumeMilitaryBullet, ResumeProject, ResumeSkill } from 'app/models/Resume';
import { Authentication } from 'app/services/Authentication';
import { Validation } from 'app/services/Validation';

@Component({
  selector: 'main-resume-editor',
  templateUrl: './editor.component.html',
  styleUrls: [ './editor.component.css' ],
  imports: [FormsModule, CommonModule, RouterModule]
})
export class ResumesEditorComponent {

  public resume: Resume = new Resume;
  public isNewResume: boolean = true;

  public ErrorMsg: string = "";

  constructor( private http: HttpClient, private router: Router, private route: ActivatedRoute, private title: Title, public auth: Authentication, public validator: Validation ) {
    this.title.setTitle("Resume - Editor | BoredCareers");
    if (!this.auth.isLoggedIn){
      this.router.navigate(["/"]);
    }
  };

  ngOnInit(){
    this.route.queryParams.subscribe(params => {
      const ResumeID = params['ResumeID'] ? +params['ResumeID'] : null;
      if (ResumeID !== null){
        this.http.get<Resume>("api/resume?ResumeID=" + ResumeID).subscribe({
          next: data => {

            data.trackUUID = crypto.randomUUID();
            data.certifications.forEach(element => {
              element.trackUUID = crypto.randomUUID();
            });
            data.educations.forEach(element => {
              element.trackUUID = crypto.randomUUID();
            });
            data.experiences.forEach(element => {
              element.trackUUID = crypto.randomUUID();
              element.experienceBullets.forEach(subelement => {
                subelement.trackUUID = crypto.randomUUID();
              });
            });
            data.languages.forEach(element => {
              element.trackUUID = crypto.randomUUID();
            });
            if (data.military){
              data.military.trackUUID = crypto.randomUUID();
              data.military.militaryBullets.forEach(element => {
                element.trackUUID = crypto.randomUUID();
              });
            }
            data.projects.forEach(element => {
              element.trackUUID = crypto.randomUUID();
            });
            data.skills.forEach(element => {
              element.trackUUID = crypto.randomUUID();
            });

            this.resume = data;
            this.milCache = data.military;
            this.isNewResume = false;
          },
          error: err => {
            this.ErrorMsg = err.error;
          }
        });
      }
    });
  }

  SubmitForm(resume: Resume){
    resume.accountID = this.auth.loggedInUser.id;
    this.http.post("api/resume", resume).subscribe({
      next: data => {
        this.router.navigate(["/resumes"]);
      },
      error: err => {
        this.ErrorMsg = err.error;
      }
    });
  }

  validatePhone(input: string){
    let result = this.validator.validatePhoneNumber(input);
    this.resume.phoneNumber = result[1];
  }

  validateEmail(input: string){
    let result = this.validator.validateEmail(input);
    this.resume.email = result[1];
  }

  validateCertURL(input: ResumeCertification){
    let result = this.validator.validateURL(input.verificationURL);
    input.verificationURL = result[1];
  }

  validateProjectURL(input: ResumeProject){
    let result = this.validator.validateURL(input.url);
    input.url = result[1];
  }

  addExperience(){
    this.resume.experiences.push( new ResumeExperience );
  }
  delExperience(self: ResumeExperience){
    for(let i=0; i<this.resume.experiences.length; i++){
      let cur = this.resume.experiences[i];
      if (cur.trackUUID === self.trackUUID){
        this.resume.experiences.splice( i, 1 );
        break;
      }
    }
  }

  addJobFunction(self: ResumeExperience){
    self.experienceBullets.push( new ResumeExperienceBullet );
  }
  delJobFunction(self: ResumeExperience, me: ResumeExperienceBullet){
    for(let i=0; i<self.experienceBullets.length; i++){
      let cur = self.experienceBullets[i];
      if (cur.trackUUID === me.trackUUID){
        self.experienceBullets.splice( i, 1 );
        break;
      }
    }
  }

  milCache: ResumeMilitary | null = new ResumeMilitary;
  onVeteranChange(event: Event){
    const checkbox = event.target as HTMLInputElement;
    const isChecked = checkbox.checked;
    if (isChecked){
      this.resume.military = this.milCache;
    } else {
      this.resume.military = null;
    }
  }
  addMillitaryBullet(){
    this.resume.military?.militaryBullets.push( new ResumeMilitaryBullet );
  }
  delMillitaryBullet(self: ResumeMilitaryBullet){
    if (this.resume.military !== null){
      for(let i=0; i<this.resume.military.militaryBullets.length; i++){
        let cur = this.resume.military.militaryBullets[i];
        if (cur.trackUUID === self.trackUUID){
          this.resume.military.militaryBullets.splice( i, 1 );
          break;
        }
      }
    }
  }

  addEducation(){
    this.resume.educations.push( new ResumeEducation );
  }
  delEducation(self: ResumeEducation){
    for(let i=0; i<this.resume.educations.length; i++){
      let cur = this.resume.educations[i];
      if (cur.trackUUID === self.trackUUID){
        this.resume.educations.splice( i, 1 );
        break;
      }
    }
  }

  addSkill(){
    this.resume.skills.push( new ResumeSkill );
  }
  delSkill(self: ResumeSkill){
    for(let i=0; i<this.resume.skills.length; i++){
      let cur = this.resume.skills[i];
      if (cur.trackUUID === self.trackUUID){
        this.resume.skills.splice( i, 1 );
        break;
      }
    }
  }

  addLanguage(){
    this.resume.languages.push( new ResumeLanguage );
  }
  delLanguage(self: ResumeLanguage){
    for(let i=0; i<this.resume.languages.length; i++){
      let cur = this.resume.languages[i];
      if (cur.trackUUID === self.trackUUID){
        this.resume.languages.splice( i, 1 );
        break;
      }
    }
  }

  addCert(){
    this.resume.certifications.push( new ResumeCertification );
  }
  delCert(self: ResumeCertification){
    for(let i=0; i<this.resume.certifications.length; i++){
      let cur = this.resume.certifications[i];
      if (cur.trackUUID === self.trackUUID){
        this.resume.certifications.splice( i, 1 );
        break;
      }
    }
  }

  addProject(){
    this.resume.projects.push( new ResumeProject );
  }
  delProject(self: ResumeProject){
    for(let i=0; i<this.resume.projects.length; i++){
      let cur = this.resume.projects[i];
      if (cur.trackUUID === self.trackUUID){
        this.resume.projects.splice( i, 1 );
        break;
      }
    }
  }

}