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.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import it.mice.voila.runtime.security.OperationAuditService;
import it.mice.voila.runtime.security.OperationConfigAttribute;
import it.mice.voila.runtime.springmvc.controller.DefaultController;
import it.mice.voila.runtime.springmvc.flashmap.FlashMap;
import it.mice.voila.runtime.springmvc.form.JfFormBean;
import it.mice.voila.runtime.springmvc.util.SpringMvcUtil;

/**
 * Spring mvc interceptor that mantain the path stack chain for go back facility.
 */
public class OperationAuditInterceptor implements HandlerInterceptor {
	public static final String OPERATION_CONFIG_ATTRIBUTE = "OPERATION_CONFIG_ATTRIBUTE";
	/**
	 * default logger.
	 */
	Log log = LogFactory.getLog(OperationAuditInterceptor.class);
	
	@Autowired
    private VelocityEngine velocityEngine;
	
	@Autowired(required=false)
    private OperationAuditService operationAuditService;

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

		OperationConfigAttribute operationConfigAttribute = (OperationConfigAttribute)SpringMvcUtil.getRequestParameterOrAttribute(OPERATION_CONFIG_ATTRIBUTE);
		if (operationConfigAttribute == null) {
			return;
		}
//		request.removeAttribute(OPERATION_CONFIG_ATTRIBUTE);
		Object handlerBean = SpringMvcUtil.getHandlerBean(handler);
		if (FlashMap.getMessages().hasErrors()) {
			return;
		}
		if (handlerBean instanceof DefaultController && operationAuditService != null) {
			JfFormBean form = SpringMvcUtil.getForm((HandlerMethod)handler);
			operationAuditService.audit(operationConfigAttribute, form);
		}
	}
}
