/**
 * 
 */
package org.yacos.web.system.validation;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.yacos.web.system.form.FormUser;

/**
 * @author christiancorsano
 *
 */
public class UserValidator implements Validator {

	/**
	 * @see org.springframework.validation.Validator#supports(java.lang.Class)
	 */
	@SuppressWarnings("unchecked")
	public boolean supports(Class commandClass) {
		return commandClass.isAssignableFrom(FormUser.class);
	}

	/**
	 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
	 */
	public void validate(Object commandObject, Errors errors) {
		FormUser userCommand = (FormUser) commandObject;
		
		validateLogin(userCommand.getLogin(), errors);
		validateEmail(userCommand.getEmail(), errors);
		validatePassword(userCommand, errors);

		// FIRSTNAME & LASTNAME VALIDATOR
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "form.register.error.firstNameEmpty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "form.register.error.lastNameEmpty");
	}
	
	// PASSWORD VALIDATOR
	public void validatePassword(FormUser userCommand, Errors errors){
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "form.register.error.passwordEmpty");
		if(userCommand.passwordWasModified() && (! userCommand.passwordsMatches())){
			errors.rejectValue("password", "form.register.error.passwordsDontMatches");
		}
	}
	
	// EMAIL VALIDATOR
	public void validateEmail(String email, Errors errors){
		email = email.toLowerCase();
		Pattern emailPattern = Pattern.compile("^[a-z0-9._-]+@[a-z0-9._-]{2,}[.][a-z]{2,4}$");	// Regex
		Matcher emailMatcher = emailPattern.matcher(email);
		
		if(!emailMatcher.matches()){
			errors.rejectValue("email", "form.register.error.emailInvalid");
		}
		ValidationUtils.rejectIfEmpty(errors, "email", "form.register.error.emailEmpty");
	}
	
	// LOGIN VALIDATOR
	public void validateLogin(String login, Errors errors){
		// 3 caractere mini, commence par un caractere
		Pattern loginPattern = Pattern.compile("^[a-zA-Z][a-zA-Z0-9._-]+$");	//Regex
		Matcher loginMatcher = loginPattern.matcher(login);
		
		if(!loginMatcher.matches()){
			errors.rejectValue("login", "form.register.error.loginInvalid");
		}
		
		if(login.length()<3){
			errors.rejectValue("login", "form.register.error.loginTooShort");
		}
	}

}
