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.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import it.mice.voila.runtime.events.OperationSuccessEvent;
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 PublishOperationSuccessEventInterceptor extends HandlerInterceptorAdapter implements ApplicationContextAware {
	/**
	 * default logger.
	 */
	private static final Log LOGGER = LogFactory.getLog(PublishOperationSuccessEventInterceptor.class);
	private ApplicationContext applicationContext;
	/* (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 {

		Object handlerBean = SpringMvcUtil.getHandlerBean(handler);
		if (FlashMap.getMessages().hasErrors()) {
			return;
		}
		OperationConfigAttribute operationConfigAttribute = (OperationConfigAttribute)SpringMvcUtil.getRequestParameterOrAttribute(OperationAuditInterceptor.OPERATION_CONFIG_ATTRIBUTE);
		if (operationConfigAttribute == null) {
			return;
		}
		if (handlerBean instanceof DefaultController) {
			JfFormBean form = SpringMvcUtil.getForm((HandlerMethod)handler);
			if (form != null) {
				if (LOGGER.isDebugEnabled()) {
					LOGGER.debug("Publish new operation success event for " + operationConfigAttribute);
				}
				applicationContext.publishEvent(new OperationSuccessEvent(operationConfigAttribute.getOperationName(), form));
			}
		}
		super.afterCompletion(request, response, handler, ex);
	}

	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
