package org.seasar.jsf.template.impl;

import javax.faces.component.UICommand;
import javax.faces.component.UIComponent;
import javax.faces.el.MethodBinding;

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

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

	private static final String LOCATION_HREF = "location.href";
	
	public AbstractUICommandBuilder(String namespaceURI, String localName,
			String qName, Attributes attributes) {
		
		super(namespaceURI, localName, qName, attributes);
		addCustomPropertyName(JsfConstants.ACTION_ATTR);
		addCustomPropertyName(JsfConstants.ONCLICK_ATTR);
	}
	
	
	/**
	 * @see org.seasar.jsf.template.impl.AbstractComponentTreeBuilder#setProperties(javax.faces.component.UIComponent)
	 */
	protected void setProperties(UIComponent component) {
		super.setProperties(component);
		String action = (String) getProperty(JsfConstants.ACTION_ATTR);
		if (!StringUtil.isEmpty(action)) {
			MethodBinding binding = null;
			if (BindingUtil.isValueReference(action)) {
				binding = new MethodBindingImpl(action);
			} else {
				binding = new SimpleMethodBinding(action);
			}
			((UICommand) component).setAction(binding);
		}
		String onclick = (String) getProperty(JsfConstants.ONCLICK_ATTR);
		if (!StringUtil.isEmpty(onclick) && onclick.length() > LOCATION_HREF.length()) {
			String s = onclick.substring(0, LOCATION_HREF.length());
			if (LOCATION_HREF.equalsIgnoreCase(s)) {
				int index = onclick.indexOf(JsfConstants.JS_STMT_END);
				if (index > 0) {
					onclick = onclick.substring(index + 1);
					component.getAttributes().put(JsfConstants.ONCLICK_ATTR, onclick);
				}
			}
		}
	}
}
