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

import it.mice.voila.runtime.exception.BusinessException;
import it.mice.voila.runtime.security.ProcessSecurityBean;
import it.mice.voila.runtime.springmvc.controller.DefaultController;
import it.mice.voila.runtime.springmvc.form.JfFormBean;
import it.mice.voila.runtime.springmvc.util.SpringMvcUtil;
import it.mice.voila.runtime.util.UserMessage;
import it.mice.voila.runtime.web.menu.MenuFilterManager;

import java.util.Enumeration;

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.MethodParameter;
import org.springframework.web.bind.support.WebRequestDataBinder;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class AdvancedSecurityCheckInterceptor extends HandlerInterceptorAdapter {
	Log log = LogFactory.getLog(AdvancedSecurityCheckInterceptor.class);
	public static final String PERFORM_AUTH_RULE_SECURITY_CHECK = "performAuthRuleSecurityCheck";
    private  MenuFilterManager menuFilterManager;
	
	/**
	 * @return the menuFilterManager
	 */
	public MenuFilterManager getMenuFilterManager() {
		return menuFilterManager;
	}

	/**
	 * @param menuFilterManager the menuFilterManager to set
	 */
	public void setMenuFilterManager(MenuFilterManager menuFilterManager) {
		this.menuFilterManager = menuFilterManager;
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		Object handlerBean = SpringMvcUtil.getHandlerBean(handler);
		if (handlerBean instanceof DefaultController) {
			Boolean check = (Boolean)request.getAttribute(PERFORM_AUTH_RULE_SECURITY_CHECK);
			if (check != null) {
				JfFormBean form = SpringMvcUtil.getForm((HandlerMethod)handler);
				if (form != null) {
					ProcessSecurityBean bean = new ProcessSecurityBean(request.getServletPath(), null);
					WebRequest webRequest = new ServletWebRequest(request, response);
					WebRequestDataBinder binder = new WebRequestDataBinder(form);
					binder.bind(webRequest);

					request.removeAttribute(PERFORM_AUTH_RULE_SECURITY_CHECK);
					boolean isAuthorizationDenied = menuFilterManager.disableMenuItem(bean);
				    if (isAuthorizationDenied) {
				    	UserMessage userMessage = new UserMessage("message.notAuthorizedUser");
				    	throw new BusinessException(userMessage);
				    }
				}
			}
		}
		return true;
	}
}
