package inc.monsters.mias.validators;

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

public class CaptchaValidator implements Validator {

	public void validate(FacesContext context,
						 UIComponent  toValidate, 
						 Object       o)         throws ValidatorException {
		
		boolean valid = true;
		String value = "";
		
		if (null != o && o instanceof String) {
			value = (String) o;
			if (!value.equals(getCaptcha(context))) {
				valid = false;
			}
		} else {
			valid = false;
		}
		
		if (!valid) {
			((UIInput) toValidate).setValid(false);
			FacesMessage message = new FacesMessage("Invalid captcha, please try again.");
			throw new ValidatorException(message);
		}
	}
	
	private String getCaptcha(FacesContext context) {
		return (String)context.getExternalContext().getSessionMap().get("captcha");
	}
}
