/*
 * 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.xwork2.interceptor;

import nuts.core.orm.dao.DataAccessClient;
import nuts.core.orm.dao.DataAccessSession;
import nuts.core.orm.dao.DataAccessSessionAware;
import nuts.core.orm.dao.DataAccessUtils;

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 DataAccessClient dataAccessClient;

	/**
	 * @param dataAccessClient the dataAccessClient to set
	 */
	@Inject(required=false)
	public void setDataAccessClient(DataAccessClient 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 DataAccessSessionAware) {
				DataAccessSession dataAccessSession = dataAccessClient.openSession(autoCommit);
				((DataAccessSessionAware)action).setDataAccessSession(dataAccessSession);
				try {
					return actionInvocation.invoke();
				}
				finally {
					DataAccessUtils.closeQuietly(dataAccessSession);
				}
			}
		}
		return actionInvocation.invoke();
	}
}
