import { Component } from '@angular/core';
import { CvService } from '../services/cv.service';
import { IContact } from './contact.model';
import { FormBuilder, FormControl, NgForm } from '@angular/forms';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrl: './contact.component.scss'
})
export class ContactComponent {
  messageModel: IContact = {name: '', email: '', content: '' };
  candidateId: number = 1;
  messageSentError: boolean = false;
  messageSentSuccess: boolean = false;
  submitted: boolean = false;

  constructor(private svc: CvService, private formBuilder: FormBuilder){
  }

  sendMessage(messageForm: NgForm) :void{
    this.submitted = true;
    if(messageForm.valid){
      this.messageSentError = false;
      this.messageSentSuccess = false;

    this.svc.sendMessage(this.messageModel, this.candidateId).subscribe({
      next: (response) => this.messageSentSuccess = response,
      error: () => this.messageSentError = true
    });
    }
    else{
        this.validateAllFormFields(messageForm);
    }
    
  }

  validateAllFormFields(formGroup: NgForm) {          
    Object.keys(formGroup.controls).forEach(field => {    
      const control = formGroup.controls[field];              
      if (control instanceof FormControl) {               
        control.markAsTouched({ onlySelf: true });
      } else if (control instanceof NgForm) {         
        this.validateAllFormFields(control);             
      }
    });
  }
}


