import { CommonModule } from '@angular/common'; import { Component } from '@angular/core'; import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, Validators, } from '@angular/forms'; import { Router } from '@angular/router'; import { Subscription } from 'rxjs'; import { User } from '../../model/User'; import { ModalService } from '../../services/modal/modal.service'; import { AuthService } from '../../services/auth/auth.service'; @Component({ selector: 'app-register-page', imports: [FormsModule, ReactiveFormsModule, CommonModule], templateUrl: './register-page.component.html', }) export class RegisterPageComponent { userForm: FormGroup; user: User = { login: '', password: '' }; errorMessage: string = ''; isRegisterModalOpen: boolean = false; modalId: string = 'register-modal'; private modalSub!: Subscription; constructor( private authService: AuthService, private fb: FormBuilder, private modalService: ModalService, private router: Router ) { this.userForm = this.fb.group( { login: [ this.user.login, [Validators.required, Validators.minLength(3)], ], password: [ this.user.password, [Validators.required, Validators.minLength(6)], ], verifyPassword: ['', [Validators.required]], }, { validator: this.passwordMatchValidator } ); } ngOnInit() { this.modalSub = this.modalService .getModalState(this.modalId) .subscribe((open) => { this.isRegisterModalOpen = open; }); } ngOnDestroy() { this.modalSub.unsubscribe(); } passwordMatchValidator(formGroup: FormGroup) { const password = formGroup.get('password')?.value; const verifyPassword = formGroup.get('verifyPassword')?.value; return password === verifyPassword ? null : { mismatch: true }; } public register() { if (this.userForm.invalid) { this.errorMessage = 'Veuillez remplir tous les champs (identifiant de 3 caractères et mot de passe de 6 caractères minimum)'; return; } this.user.login = this.userForm.value.login; this.user.password = this.userForm.value.password; this.authService .register(this.user.login, this.user.password) .subscribe({ next: () => { this.closeRegisterModal(); setTimeout(() => { this.router.navigate(['/map', {tutorial: true}]); }, 1); }, error: (response) => { console.error('Register KO: ', response.error.detail); this.errorMessage = response.error.detail; }, }); } openRegisterModal() { this.modalService.openModal(this.modalId); } closeRegisterModal() { this.modalService.closeModal(this.modalId); } openLoginModal() { this.modalService.closeModal(this.modalId); this.modalService.openModal('login-modal'); } }