import { UsersService } from './../../../../services/users.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { User } from './../../../../models/userResponse';
import { Component, Inject, OnInit } from '@angular/core';


@Component({
  selector: 'app-edit-profil-info-connexion',
  templateUrl: './edit-profil-info-connexion.component.html',
  styleUrls: ['./edit-profil-info-connexion.component.scss']
})
export class EditProfilInfoConnexionComponent implements OnInit {

  constructor(@Inject(MAT_DIALOG_DATA) public element: User,  public dialogRef: MatDialogRef<EditProfilInfoConnexionComponent>,
    private formBuilder: FormBuilder, private usersService: UsersService)
   {}
   formGroup: FormGroup;
   submitted = false;
   user = this.element


   ngOnInit(): void {

    this.createForm(); 
  }



  createForm() {
   
    let emailregex: RegExp = /^(([^<>()\[\]\\.,;:\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,}))$/;
    this.formGroup = this.formBuilder.group({
      email: [null, [Validators.required, Validators.pattern(emailregex)]],
      password: [null, [Validators.required, this.checkPassword]]
    });
  }

  

  checkPassword(control) {
    let enteredPassword = control.value
    let passwordCheck = /^(?=.*[A-Z])(?=.*[a-z])(?=.{8,})/;
    return (!passwordCheck.test(enteredPassword) && enteredPassword) ? { 'requirements': true } : null;
  }

  getErrorEmail() {
    return this.formGroup.get('email').hasError('required') ? 'Adresse email requise' :
      this.formGroup.get('email').hasError('pattern') ? 'Adresse email non valide' : '';
  }

  getErrorPassword() {
    return this.formGroup.get('password').hasError('required') ? 'Mot de passe requis' :
      this.formGroup.get('password').hasError('requirements') ? 
      'Le mot de passe doit comporter au moins 8 caractères, une lettre majuscule,  une lettre majuscule' : '';
  }

  


 // login
 updateProfil(){

  this.submitted = true;
  if (this.formGroup.invalid) {
    return;
  }
  this.usersService.editOneUser(this.element._id, this.formGroup.value).subscribe(
    data => {
        // this.router.navigate([this.returnUrl]);
        console.log(data)
        // this.loading = false;
        // this.router.navigate(['auth']);
    },
    err => {
        // this.loading = false;
        // console.log(err.error.message)
        // this.authService.openSnackBar(err.error.message)
    });
}


  
  onConfirm(): void {
    // Close the dialog, return true
    this.dialogRef.close(true);
  }

  onNoClick(): void {
    this.dialogRef.close(false);
  }

}