package inc.monsters.mias.extval;

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

import org.apache.myfaces.extensions.validator.baseval.annotation.Pattern;
import org.apache.myfaces.extensions.validator.core.metadata.MetaDataEntry;
import org.apache.myfaces.extensions.validator.core.validation.strategy.AbstractAnnotationValidationStrategy;

public class PatternOrValidationStrategy extends
		AbstractAnnotationValidationStrategy<Pattern> {

	@Override
	protected String getValidationErrorMsgKey(Pattern annotation) {
		return annotation.validationErrorMsgKey();
	}

	@Override
	protected void processValidation(FacesContext facesContext,
								     UIComponent uiComponent, 
								     MetaDataEntry metaDataEntry,
								     Object convertedObject) throws ValidatorException {

		Pattern annotation = metaDataEntry.getValue(Pattern.class);
		
		boolean matched = false;
		String expressions = null;
		for (String expression : annotation.value()) {
			if (   convertedObject != null 
				&& java.util.regex.Pattern.compile(expression).matcher(convertedObject.toString()).matches()) {
				matched = true;
				break;
			} else {
				if (expressions == null) {
					expressions = expression;
				} else {
					expressions += ", " + expression;
				}
			}
		}
		
		if(!matched) {
			throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
														  getErrorMessageSummary(annotation),
														  getErrorMessageDetail(annotation).replace("{0}",expressions)));
		}
	}
}
