package org.seasar.jsf.template.impl;

import javax.faces.application.Application;
import javax.faces.component.EditableValueHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.faces.validator.Validator;

import org.seasar.framework.util.StringUtil;
import org.seasar.jsf.JsfConstants;
import org.seasar.jsf.util.BindingUtil;
import org.xml.sax.Attributes;

/**
 * @author higa
 *  
 */
public abstract class AbstractUIInputBuilder extends AbstractUIComponentBuilder {

	public AbstractUIInputBuilder(String namespaceURI, String localName,
			String qName, Attributes attributes) {

		super(namespaceURI, localName, qName, attributes);
		addCustomPropertyName(JsfConstants.VALIDATORS_ATTR);
	}

	/**
	 * @see org.seasar.jsf.template.impl.AbstractComponentTreeBuilder#setProperties(javax.faces.component.UIComponent)
	 */
	protected void setProperties(UIComponent component) {
		super.setProperties(component);
		String validators = (String) getProperty(JsfConstants.VALIDATORS_ATTR);
		if (!StringUtil.isEmpty(validators)
				&& component instanceof EditableValueHolder) {
			EditableValueHolder evh = (EditableValueHolder) component;
			if (BindingUtil.isValueReference(validators)) {
				validators = BindingUtil.removeBinding(validators);
			}
			String[] validatorNames = StringUtil.split(validators, ", ");
			FacesContext context = FacesContext.getCurrentInstance();
			Application app = context.getApplication();
			for (int i = 0; i < validatorNames.length; ++i) {
				ValueBinding binding = app.createValueBinding(BindingUtil
						.getValueReference(validatorNames[i]));
				Validator validator = (Validator) binding.getValue(context);
				evh.addValidator(validator);
			}
		}
	}
}