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

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.HandlerInterceptor;

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

public class PerformanceLoggerInterceptor implements HandlerInterceptor {

	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 {
//        Enumeration headerNames = request.getHeaderNames();
//        while(headerNames.hasMoreElements()) {
//          String headerName = (String)headerNames.nextElement();
//          log.warn(headerName + "=" + request.getHeader(headerName));
//        }
		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 true;
	}

	@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));
        }
	}
}
