/**
 * 
 */
package org.richfaces.ui.application;

import javax.el.ELContext;
import javax.el.MethodExpression;
import javax.el.MethodInfo;
import javax.el.MethodNotFoundException;
import javax.el.ValueExpression;
import javax.faces.context.FacesContext;

/**
 * @author asmirnov
 * 
 */
public class StateMethodExpressionWrapper extends MethodExpression {

	private MethodExpression parent;
	
	private ValueExpression baseObjectExpression = null;

	/**
	 * @param parent
	 */
	public StateMethodExpressionWrapper(MethodExpression parent,ValueExpression baseObject) {
		this.parent = parent;
		this.baseObjectExpression = baseObject;
	}

	/**
	 * @return
	 * @see javax.el.Expression#getExpressionString()
	 */
	public String getExpressionString() {
		return parent.getExpressionString();
	}

	/**
	 * @param context
	 * @return
	 * @see javax.el.MethodExpression#getMethodInfo(javax.el.ELContext)
	 */
	public MethodInfo getMethodInfo(ELContext context) {
		MethodInfo methodInfo = parent.getMethodInfo(context);
		return methodInfo;
	}

	/**
	 * @param context
	 * @param params
	 * @return
	 * @see javax.el.MethodExpression#invoke(javax.el.ELContext,
	 *      java.lang.Object[])
	 */
	public Object invoke(ELContext context, Object[] params) {
		Object result;
		try {
			result = parent.invoke(context, params);
		} catch (MethodNotFoundException e) {
			Object base = baseObjectExpression.getValue(context);
			if (base instanceof MethodExpression) {
				MethodExpression referencedMethod = (MethodExpression) base;
				result = referencedMethod.invoke(context, params);
			} else {
				throw e;
			}
		}
		return result;
	}

	/**
	 * @return
	 * @see javax.el.Expression#isLiteralText()
	 */
	public boolean isLiteralText() {
		return parent.isLiteralText();
	}

	/**
	 * @param obj
	 * @return
	 * @see javax.el.Expression#equals(java.lang.Object)
	 */
	public boolean equals(Object obj) {
		return parent.equals(obj);
	}

	/**
	 * @return
	 * @see javax.el.Expression#hashCode()
	 */
	public int hashCode() {
		return parent.hashCode();
	}

	/**
	 * @return
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		return parent.toString();
	}

}
