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

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import nuts.aems.WebApplet;
import nuts.aems.action.resource.ResourceLoadAction;
import nuts.aems.action.template.TemplateLoadAction;
import nuts.aems.constant.AC;
import nuts.core.orm.dao.DataAccessSession;
import nuts.core.orm.dao.DataAccessUtils;
import nuts.exts.xwork2.util.ContextUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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

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

	protected static Log log = LogFactory.getLog(MemCacheInterceptor.class);

	@SuppressWarnings("unchecked")
	public static void setCacheReloadTime(String name, boolean reset) {
		Date d = Calendar.getInstance().getTime();
		
		ContextUtils.getApplication().put(name, d);
		
		if (reset || WebApplet.get().getCache().get(name) == null) {
			WebApplet.get().getCache().put(name, d);
		}
	}
	
	protected boolean needLoad(Map cache, Map app, String name) {
		Object c = cache.get(name);
		Object a = app.get(name);
		
		if (c == null || a == null) {
			return true;
		}
		if (!(a instanceof Date)) {
			return false;
		}
		if (((Date)c).after((Date)a)) {
			return true;
		}
		return false;
	}

	protected void preProcess(Map cache, Map apc, DataAccessSession das) throws Exception {
	}
	
	protected void postProcess(Map cache, Map apc, DataAccessSession das) throws Exception {
	}
	
	/**
	 * 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 {
		long startTime = System.currentTimeMillis();
		
		DataAccessSession das = WebApplet.get().openDataAccessSession();
		try {
			Map cache = WebApplet.get().getCache();
			Map apc = ContextUtils.getApplication();

			preProcess(cache, apc, das);
			
			if (WebApplet.get().getDatabaseResourceLoader() != null) {
				if (needLoad(cache, apc, AC.RESOURCE_RELOAD)) {
					ResourceLoadAction a = new ResourceLoadAction();
					a.setReset(false);
					a.setDataAccessSession(das);
					a.load();
				}
			}

			if (WebApplet.get().getDatabaseTemplateLoader() != null) {
				if (needLoad(cache, apc, AC.TEMPLATE_RELOAD)) {
					TemplateLoadAction a = new TemplateLoadAction();
					a.setReset(false);
					a.setDataAccessSession(das);
					a.load();
				}
			}

			postProcess(cache, apc, das);
		}
		finally {
			DataAccessUtils.closeQuietly(das);
		}

		log.debug("MemCache " + (System.currentTimeMillis() - startTime));
		
		return actionInvocation.invoke();
	}

}
