package it.mice.voila.runtime.springmvc.interceptors;

import it.mice.voila.runtime.springmvc.util.SpringMvcUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * Spring MVC Request interceptor that resolve requests for 
 *
 */
public class GoBackRequestInterceptor extends HandlerInterceptorAdapter {
	public static final String SPECIAL_GO_BACK = "special.goBack";
	public static final String SPECIAL_END_FLOW = "special.endFlow";
	public static final String SPECIAL_REFRESH = "special.refresh";
	
	private static final Log log = LogFactory.getLog(GoBackRequestInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		if (request.getRequestURI().contains(SPECIAL_GO_BACK)) {
			if (log.isDebugEnabled()) {
				log.debug("GoBack intercepted, proceding with the last saved successully executed command...");
			}
			SpringMvcUtil.doLastPathRedirect(request, response, request.getRequestURI(), 2);
			return false;
		}
		if (request.getRequestURI().contains(SPECIAL_END_FLOW)) {
			if (log.isDebugEnabled()) {
				log.debug("EndFlow intercepted, proceding with the last saved successully executed command before starting current ending flow...");
			}
			SpringMvcUtil.doPrevFlowRedirect(request, response, request.getRequestURI());
			return false;
		}
		if (request.getRequestURI().contains(SPECIAL_REFRESH)) {
			if (log.isDebugEnabled()) {
				log.debug("Refresh page intercepted, proceding with the last saved successully executed command...");
			}
			SpringMvcUtil.doLastPathRedirect(request, response, request.getRequestURI(), 1);
			return false;
		}
		return super.preHandle(request, response, handler);
	}

}
