package org.jboss.installer.validators;

import org.jboss.installer.core.LanguageUtils;
import org.jboss.installer.core.ValidationResult;

public class PasswordSecurityValidator {

    public static final String NON_ALPHA_NUMERIC_REGEX = "^.*[^a-zA-Z0-9 ].*$";
    public static final String NO_DIGIT_REGEX = ".*\\d.*";
    public static final String NO_ALPHABETIC_REGEX = ".*[a-zA-Z].*";

    public static final String USERNAME_PASSWORD_MATCH_KEY = "admin_creation_screen.username_password_match";
    public static final String PASSWORD_LENGTH_KEY = "admin_creation_screen.password_length";
    public static final String PASSWORD_ANY_DIGIT_KEY = "admin_creation_screen.password_any_digit";
    public static final String PASSWORD_ANY_ALPHABETIC_KEY = "admin_creation_screen.password_any_alphabetic";
    public static final String PASSWORD_ANY_NON_ALPHA_NUM_KEY = "admin_creation_screen.password_any_non_alpha_num";
    public static final String PASSWORD_VALIDATION_WARNING_KEY = "admin_creation_screen.password_validation_warning";

    private final LanguageUtils langUtils;

    public PasswordSecurityValidator(LanguageUtils langUtils) {
            this.langUtils = langUtils;
    }

    public ValidationResult passwordSecurityCheck(String username, String password) {
        if (password.length() < 8) {
            return ValidationResult.warning(langUtils.getString(PASSWORD_LENGTH_KEY));
        }
        if (!password.matches(NO_ALPHABETIC_REGEX)) {
            return ValidationResult.warning(langUtils.getString(PASSWORD_ANY_ALPHABETIC_KEY));
        }
        if (!password.matches(NO_DIGIT_REGEX)) {
            return ValidationResult.warning(langUtils.getString(PASSWORD_ANY_DIGIT_KEY));
        }
        if (!password.matches(NON_ALPHA_NUMERIC_REGEX)) {
            return ValidationResult.warning(langUtils.getString(PASSWORD_ANY_NON_ALPHA_NUM_KEY));
        }
        if (password.equals(username)) {
            return ValidationResult.warning(langUtils.getString(USERNAME_PASSWORD_MATCH_KEY));
        }
        return ValidationResult.ok();
    }

    public ValidationResult passwordValidationWarning(String username, String password) {
        if (passwordSecurityCheck(username, password).getResult().equals(ValidationResult.Result.OK)) {
            return ValidationResult.ok();
        }
        return ValidationResult.warning(langUtils.getString(PASSWORD_VALIDATION_WARNING_KEY));
    }
}
