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.web.servlet.handler.HandlerInterceptorAdapter;

public class PerformanceLoggerInterceptor extends HandlerInterceptorAdapter {

	Log log = LogFactory.getLog(PerformanceLoggerInterceptor.class);
	String START_TIME = PerformanceLoggerInterceptor.class.getName() + ".startTime";
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if (!(handler instanceof DefaultController)) {
			return true;
		}

        if (log.isInfoEnabled()) {
            //log.info("Start Transaction '" + ctx.getOperationName() + "' Method=" + request.getMethod() + " ...");
            log.info("Start Transaction '" + request.getRequestURI() + "' on handler '" + handler + "' Method='" + request.getMethod() + "' ...");
            request.setAttribute(START_TIME, new Long(System.currentTimeMillis()));
        }
		return super.preHandle(request, response, handler);
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if (!(handler instanceof DefaultController)) {
			return;
		}
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("mm:ss:SSS");
        if (SpringMvcUtil.getRequest().getAttribute(START_TIME) != null) {
            long dStart = ((Long) SpringMvcUtil.getRequest().getAttribute(START_TIME)).longValue();
            long diff = System.currentTimeMillis() - dStart;
            java.util.Date dDiff = new java.util.Date(diff);
            log.info("End Transaction. Elapsed: " + sdf.format(dDiff));
        }

		super.afterCompletion(request, response, handler, ex);
	}
}
