/**
 * 
 */
package org.richfaces.validator;

import javax.el.ELException;
import javax.el.ValueExpression;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.EditableValueHolder;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 * Implementation of the JSF validator to use with Bean Validation / Hibernate
 * validator
 * 
 * @author asmirnov
 * 
 */
public class FacesBeanValidator implements Validator {

	public static final String BEAN_VALIDATOR_TYPE = "org.richfaces.BeanValidator";

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.faces.validator.Validator#validate(javax.faces.context.FacesContext,
	 *      javax.faces.component.UIComponent, java.lang.Object)
	 */
	public void validate(FacesContext context, UIComponent component,
			Object convertedValue) throws ValidatorException {
		if (component instanceof EditableValueHolder) {
			// Validate input component
			EditableValueHolder input = (EditableValueHolder) component;
			try {
				ValueExpression valueExpression = component
						.getValueExpression("value");
				if (null != valueExpression) {
					// TODO - check EL Exceptions ?
					String[] messages = BeanValidator.getInstance(context)
							.validate(context, valueExpression, convertedValue);
					if (null != messages) {
						input.setValid(false);
						// send all validation messages.
						for (String msg : messages) {
							// TODO - create Summary message ?
							context.addMessage(component.getClientId(context), new FacesMessage(
									FacesMessage.SEVERITY_ERROR, "", msg));
						}
					}
				}
			} catch (ELException e) {
				throw new FacesException(e);
			}
		}
	}
}
