/*
 * This file is part of Nuts Framework.
 * Copyright (C) 2009 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 *
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.exts.struts2.interceptor;

import nuts.core.lang.ClassUtils;
import nuts.exts.struts2.NutsStrutsConstants;
import nuts.exts.struts2.actions.ActionConstants;
import nuts.exts.struts2.actions.ActionConstsAware;
import nuts.exts.struts2.actions.ActionUtilities;
import nuts.exts.struts2.actions.ActionUtilsAware;
import nuts.exts.struts2.actions.CommonAction;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

@SuppressWarnings("serial")
public class ActionHelperInterceptor extends AbstractInterceptor {

	private Class consts;

	private Class utils;

	/**
	 * Constructor
	 */
	public ActionHelperInterceptor() {
	}

	/**
	 * @param consts the consts to set
	 */
	@Inject(value = NutsStrutsConstants.NUTS_ACTION_CONSTS, required = false)
	public void setConsts(String consts) throws Exception {
		this.consts = ClassUtils.getClass(consts);
	}

	/**
	 * @param utils the utils to set
	 */
	@Inject(value = NutsStrutsConstants.NUTS_ACTION_UTILS, required = false)
	public void setUtils(String utils) throws Exception {
		this.utils = ClassUtils.getClass(utils);
	}

	/**
	 * Allows the Interceptor to do some processing on the request before and/or after the rest of
	 * the processing of the request by the {@link ActionInvocation} or to short-circuit the
	 * processing and just return a String return code.
	 * 
	 * @param invocation the action invocation
	 * @return the return code, either returned from {@link ActionInvocation#invoke()}, or from the
	 *         interceptor itself.
	 * @throws Exception any system-level error, as defined in
	 *             {@link com.opensymphony.xwork2.Action#execute()}.
	 */
	public String intercept(ActionInvocation invocation) throws Exception {
		final Object action = invocation.getAction();

		if (consts != null && action instanceof ActionConstsAware) {
			((ActionConstsAware)action).setConsts(
				(ActionConstants)ClassUtils.newInstance(consts, action, CommonAction.class));
		}
		if (utils != null && action instanceof ActionUtilsAware) {
			((ActionUtilsAware)action).setUtils(
				(ActionUtilities)ClassUtils.newInstance(utils, action, CommonAction.class));
		}

		return invocation.invoke();
	}
}
