/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 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.xwork2.interceptor;

import nuts.core.dao.DaoClient;
import nuts.core.dao.DaoSession;
import nuts.core.dao.DaoSessionAware;
import nuts.core.dao.DaoUtils;

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

/**
 */
@SuppressWarnings("serial")
public class DataAccessSessionInterceptor extends AbstractInterceptor {

	protected boolean autoCommit = false;
	protected DaoClient dataAccessClient;

	/**
	 * @param dataAccessClient the dataAccessClient to set
	 */
	@Inject(required=false)
	public void setDataAccessClient(DaoClient dataAccessClient) {
		this.dataAccessClient = dataAccessClient;
	}

	/**
	 * @param autoCommit the autoCommit to set
	 */
	public void setAutoCommit(String autoCommit) {
		this.autoCommit = Boolean.valueOf(autoCommit);
	}

	/**
	 * 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 actionInvocation 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 actionInvocation) throws Exception {
		if (dataAccessClient != null) {
			Object action = actionInvocation.getAction();
			if (action instanceof DaoSessionAware) {
				DaoSession dataAccessSession = dataAccessClient.openSession(autoCommit);
				((DaoSessionAware)action).setDataAccessSession(dataAccessSession);
				try {
					return actionInvocation.invoke();
				}
				finally {
					DaoUtils.safeClose(dataAccessSession);
				}
			}
		}
		return actionInvocation.invoke();
	}
}
