import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { InfoService } from '../services/info.service';

@Component({
  selector: 'app-account',
  standalone: false,
  templateUrl: './account.component.html',
  styleUrl: './account.component.css'
})

export class AccountComponent {
  infoForm: FormGroup;
  infos: any[] = [];

  constructor(private fb: FormBuilder, private infoService: InfoService) {
    this.infoForm = this.fb.group({
      gender: ['', Validators.required],
      nameLast: ['', [Validators.required, Validators.minLength(3)]],
      nameFirst: ['', [Validators.required, Validators.minLength(3)]],
      email: ['', [Validators.required, Validators.pattern(/^[a-zA-Z0-9._%+-]+$/)]],
      address: ['', [Validators.required, Validators.minLength(10)]],
      codePostal: ['', [Validators.required, Validators.minLength(4), Validators.pattern(/^\d+$/)]],
    }); 
  }

  addInfo() {
    if (this.infoForm.valid) {
      const formData = this.infoForm.value;
      
      const email = formData.email.toLowerCase();
      const fullEmail = `${email}@edu.igensia.com`;
      const nameLast = formData.nameLast.toUpperCase();
      const nameFirst = formData.nameFirst.charAt(0).toUpperCase() + formData.nameFirst.slice(1).toLowerCase();

      const newInfo = {
        ...formData,
        nameLast: nameLast,
        nameFirst: nameFirst,
        email: fullEmail,
        date: new Date()
      };

      this.infos.push(newInfo);
      this.infoService.addInfo(newInfo);
      this.infoForm.reset();
    }
  }
}
