import { NotSamePasswordsMatcher } from './../new-user/new-user.component';
import { FormGroup, FormControl, Validators, ValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';

@Component({
  selector: 'app-new-password',
  templateUrl: './new-password.component.html',
  styleUrls: ['./new-password.component.css']
})
export class NewPasswordComponent implements OnInit {
  newPassword: FormGroup;
  hide: boolean;

  passMatcher = new NotSamePasswordsMatcher();

  constructor(@Inject(MAT_DIALOG_DATA) public data: any) { 
    this.newPassword = new FormGroup({
      id: new FormControl(''),
      password: new FormControl('', [Validators.required, Validators.minLength(8)]),
      password_confirmation: new FormControl('', [Validators.required, Validators.minLength(8)])
    }, this.checkPasswords);
    this.hide = true;
  }

  ngOnInit(): void {
    this.newPassword.patchValue({
      id: this.data.id,
    });
  }

  checkPasswords: ValidatorFn = (group: AbstractControl): ValidationErrors | null => {
    let pass = group.get('password')?.value;
    let confPass = group.get('password_confirmation')?.value;
    return pass === confPass ? null : { notSame: true }
  }

  getErrorMessage(control: string) {
    switch(control){
      case 'password':
        if(this.newPassword.get('password')?.hasError('required')) return "Este campo es obligatorio.";
        if(this.newPassword.get('password')?.hasError('minlength')) return "La contraseña debe tener al menos 8 caracteres.";
      break;
      case 'password_confirmation':
        if(this.newPassword.get('password_confirmation')?.hasError('required')) return "Este campo es obligatorio.";
        if(this.newPassword.get('password_confirmation')?.hasError('minlength')) return "La contraseña debe tener al menos 8 caracteres.";
        if(this.newPassword.errors != null && this.newPassword.errors!['notSame']) return "Las contraseñas no coinciden.";
      break;
    }
    
    return "A";
  }

}
