package org.seasar.jsf.util;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.el.ValueBinding;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.seasar.framework.container.S2Container;
import org.seasar.jsf.JsfConstants;

/**
 * @author higa
 *  
 */
public class BindingUtil {

	private BindingUtil() {
	}

	public static Object getValue(S2Container container, String name) {
		HttpServletRequest request = container.getRequest();
		Object var = getValue(request, name);
		if (var != null) {
			return var;
		}
		if (container.hasComponentDef(name)) {
			return container.getComponent(name);
		}
		return null;
	}
	
	public static Object getValue(HttpServletRequest request, String name) {
		Object var = request.getParameter(name);
		if (var != null) {
			return var;
		}
		var = request.getAttribute(name);
		if (var != null) {
			return var;
		}
		HttpSession session = request.getSession(false);
		if (session != null) {
			var = session.getAttribute(name);
			if (var != null) {
				return var;
			}
		}
		return null;
	}
	
	public static Object getBindingValue(UIComponent component, String propertyName) {
		ValueBinding binding = component.getValueBinding(propertyName);
		if (binding != null) {
			FacesContext ctx = FacesContext.getCurrentInstance();
			return binding.getValue(ctx);
		}
		return null;
	}
	
	public static String getValueReference(String value) {
		return JsfConstants.BINDING_START + value + JsfConstants.BINDING_END;
	}

	public static boolean isValueReference(String value) {
		if (value == null) {
			throw new NullPointerException("value");
		}
		return value.startsWith(JsfConstants.BINDING_START)
				&& value.endsWith(JsfConstants.BINDING_END);
	}
	
	public static String removeBinding(String valueReference) {
		return valueReference.substring(2, valueReference.length() - 1);
	}
}