package com.fp.armas.portal.validator;

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

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import com.fp.armas.portal.web.PortalWebResources;

/**
 * Validador que verifica que un mail este bien formado
 * @author dcruz
 *
 */
@FacesValidator(value="emailValidator")
public class EmailValidator implements Validator {
	
	private static final String REGEX_EMAIL = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
	private static final Pattern PATTERN_EMAIL = Pattern.compile(REGEX_EMAIL);
	
	@Override
	public void validate(FacesContext facesContext, UIComponent component, Object value)
			throws ValidatorException {
		if(value == null || value.toString().equals("")){
			throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, PortalWebResources.getString("error.campo.vacio"), PortalWebResources.getString("error.campo.vacio")));
		}
		Matcher emailMatcher = PATTERN_EMAIL.matcher(value.toString());
		if(!emailMatcher.matches()){
			throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, PortalWebResources.getString("error.mail.incorrecto"), PortalWebResources.getString("error.mail.incorrecto")));
		}
	}

}
