import { AbstractControl, ValidatorFn, FormGroup, Validators } from "@angular/forms";

export function ValidateStrongPassword(control: AbstractControl){
    let hasNumber = /\d/.test(control.value);
    let hasUpper = /[A-Z]/.test(control.value);
    let hasLower = /[a-z]/.test(control.value);
    if (!hasNumber || !hasUpper || !hasLower) {
        return { strongPassword: true };
    }
    return null;
}

function matchingPasswordsValidator(control: FormGroup){
    let password = control.get('password') || control.get('newPassword');
    let confirmPassword = control.get('confirmPassword') || control.get('confirmNewPassword');
    if (password.value !== confirmPassword.value)
        confirmPassword.setErrors({ passwordNotMatch: true });
    else {
        confirmPassword.setErrors(null);
        if (password.errors)
            confirmPassword.setErrors({ passwordNotValid: true });
        else
            confirmPassword.setErrors(null)
    }
    return null;
}

export const ValidateMatchingPasswords: ValidatorFn = matchingPasswordsValidator;

export const ValidateProfilePasswords: ValidatorFn = (control: FormGroup) => {
    let oldPassword = control.get('oldPassword');
    let newPassword = control.get('newPassword');
    let confirmNewPassword = control.get('confirmNewPassword');

    if (newPassword.value){
        newPassword.setValidators([Validators.minLength(8), ValidateStrongPassword]);
        if(oldPassword && !oldPassword.value){
            oldPassword.setErrors({ required: true });
        }
        matchingPasswordsValidator(control);
    }
    else{
        newPassword.setValidators([]);
        if (oldPassword)
            oldPassword.setErrors(null);
    }

    newPassword.updateValueAndValidity({
        onlySelf: true,
        emitEvent: false
    });
    
    return null;
}
