package it.mice.voila.runtime.springmvc.validation;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.springframework.beans.NotReadablePropertyException;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;

public class GroupAwareSpringValidatorAdapter extends SpringValidatorAdapter {

	private Validator targetValidator;

	public GroupAwareSpringValidatorAdapter(Validator targetValidator) {
		super(targetValidator);
		this.targetValidator = targetValidator;
	}

	public void validate(Object target, Errors errors, Class<?>... groups) {
		Set<ConstraintViolation<Object>> result = this.targetValidator.validate(target, groups);
		for (ConstraintViolation<Object> violation : result) {
			String field = violation.getPropertyPath().toString();
			FieldError fieldError = errors.getFieldError(field);
			if (fieldError == null || !fieldError.isBindingFailure()) {
				try {
					errors.rejectValue(field,
							violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(),
							getArgumentsForConstraint(errors.getObjectName(), field, violation.getConstraintDescriptor()),
							violation.getMessage());
				}
				catch (NotReadablePropertyException ex) {
					throw new IllegalStateException("JSR-303 validated property '" + field +
							"' does not have a corresponding accessor for Spring data binding - " +
							"check your DataBinder's configuration (bean property versus direct field access)", ex);
				}
			}
		}
	}
	
}
