package managedbean.validators;

import java.util.Map;

import javax.el.ValueExpression;
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 org.primefaces.PrimeFaces;
import org.primefaces.validate.ClientValidator;

import managedbean.common.ValidationUtils;
import managedbean.profile.RegisterUserMBean;
import managedbean.profile.UpdateProfileMBean;

@FacesValidator("nifValidator")
public class NifValidator implements Validator<String>, ClientValidator {

	public void validate(FacesContext context, UIComponent comp, String value) throws ValidatorException {
		String strValue = "";

		if (value != null)
			strValue = String.valueOf(value);

		if (strValue.equals(""))
			throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "El NIF no es válido", "El NIF " + strValue + " no es válido"));

		strValue = ValidationUtils.normalizeNIF(strValue);

		if (ValidationUtils.isValid(strValue) == false)
			throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "El NIF no es válido", "El NIF " + strValue + " no es válido"));

		boolean nifIsDupe = false;
		ValueExpression valueExpr = comp.getValueExpression("managedBean");

		if (valueExpr != null) {
			Object managedBean = valueExpr.getValue(context.getELContext());

			if (managedBean instanceof RegisterUserMBean) {
				RegisterUserMBean ruBean = RegisterUserMBean.class.cast(managedBean);
				nifIsDupe = ruBean.checkNIFDuplicated(strValue, ruBean.getUserType());
			} else if (managedBean instanceof UpdateProfileMBean) {
				UpdateProfileMBean upBean = UpdateProfileMBean.class.cast(managedBean);
				nifIsDupe = upBean.checkNIFDuplicated(strValue, upBean.getUserType(), upBean.getId());
			}
		}

		PrimeFaces.current().ajax().addCallbackParam("formattedNIF", strValue);

		if (nifIsDupe == true)
			throw new ValidatorException(
					new FacesMessage(FacesMessage.SEVERITY_WARN, "El NIF está duplicado", "El NIF " + strValue + " pertenece a otro usuario previamente registrado"));

		PrimeFaces.current().ajax().addCallbackParam("NIFisValid", true);
	}

	public Map<String, Object> getMetadata() {
		return null;
	}

	public String getValidatorId() {
		return "nifValidator";
	}
}
