import { FormGroup } from '@angular/forms';
import { AbstractControl, ValidationErrors } from "@angular/forms"

// custom validator to check that two fields match
export function ValidatorComponent(controlName: string, matchingControlName: string) {
    return (formGroup: FormGroup) => {
        const control = formGroup.controls[controlName];
        const matchingControl = formGroup.controls[matchingControlName];

        if (matchingControl.errors && !matchingControl.errors.mustMatch) {
          // return if another validator has already found an error on the matchingControl
          return;
        }

        // set error on matchingControl if validation fails
        if (control.value !== matchingControl.value) {
          matchingControl.setErrors({ mustMatch: true });
        } {
          matchingControl.setErrors(null);
        }
    }
}

export const PasswordStrengthValidator = function (control: AbstractControl): ValidationErrors | null {

  let value: string = control.value || '';
  let upperCaseCharacters = /[A-Z]+/g
  let lowerCaseCharacters = /[a-z]+/g
  let numberCharacters = /[0-9]+/g
  let specialCharacters = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/

  if (!value) {
    return null
  }

  if (upperCaseCharacters.test(value) === false) {
    return { passwordStrength: `La contraseña debe contener al menos una letra Mayúscula\n` };
  }

  if (lowerCaseCharacters.test(value) === false) {
    return { passwordStrength: `La contraseña debe contener al menos una letra minúscula\n` };
  }

  if (numberCharacters.test(value) === false) {
    return { passwordStrength: `La contraseña debe contener al menos un número\n` };
  }

  if (specialCharacters.test(value) === false) {
    return { passwordStrength: `La contraseña debe contener al menos un símbolo\n` };
  }

  return null;

}