package org.seasar.jsf.template.impl;

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

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

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

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

		super(namespaceURI, localName, qName, attributes);
		addCustomPropertyName(JsfConstants.ITEMS_ATTR);
		addCustomPropertyName(JsfConstants.ITEM_VALUE_ATTR);
		addCustomPropertyName(JsfConstants.ITEM_LABEL_ATTR);
		addCustomPropertyName(JsfConstants.NULL_LABEL_ATTR);
	}

	/**
	 * @see org.seasar.jsf.template.impl.AbstractComponentTreeBuilder#setProperties(javax.faces.component.UIComponent)
	 */
	protected void setProperties(UIComponent component) {
		super.setProperties(component);
		String ref = (String) getProperty(JsfConstants.ITEMS_ATTR);
		if (!StringUtil.isEmpty(ref)) {
			if (!BindingUtil.isValueReference(ref)) {
				ref = BindingUtil.getValueReference(ref);
			}
			FacesContext context = FacesContext.getCurrentInstance();
			Application app = context.getApplication();
			ValueBinding binding = app.createValueBinding(ref);
			UISelectItemsX child = new UISelectItemsX();
			String itemValue = (String) getProperty(JsfConstants.ITEM_VALUE_ATTR);
			if (!StringUtil.isEmpty(itemValue)) {
				child.setItemValue(itemValue);
			}
			String itemLabel = (String) getProperty(JsfConstants.ITEM_LABEL_ATTR);
			if (!StringUtil.isEmpty(itemLabel)) {
				child.setItemLabel(itemLabel);
			}
			String nullLabel = (String) getProperty(JsfConstants.NULL_LABEL_ATTR);
			if (itemLabel != null) {
				child.setNullLabel(nullLabel);
			}
			child.setValueBinding(JsfConstants.VALUE_ATTR, binding);
			component.getChildren().add(child);
		}
	}
}