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

import it.mice.voila.runtime.springmvc.controller.DefaultController;
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.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class ControllerBasePathExposingInterceptor extends HandlerInterceptorAdapter {
	Log log = LogFactory.getLog(ControllerBasePathExposingInterceptor.class);
	public static final String CONTROLLER_BASE_URL = "controllerBaseUrl";
	public static final String REQUEST_URL = "requestURL";
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		Object handlerBean = SpringMvcUtil.getHandlerBean(handler);
		if (handlerBean instanceof DefaultController) {
			RequestMapping mapping = AnnotationUtils.findAnnotation(handlerBean.getClass(), RequestMapping.class);
			String[] values = mapping.value();
			if (values.length > 0) {
				String value = values[0];
				value = value.substring(0, value.lastIndexOf("/") + 1);
				request.setAttribute(CONTROLLER_BASE_URL, value);
			}
		}
		request.setAttribute(REQUEST_URL, request.getRequestURL());
		return true;
	}
}
