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

import it.mice.voila.runtime.web.menu.MenuFilterManager;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.PageContext;

import org.apache.commons.lang.StringUtils;
import org.displaytag.util.AuthorizationHelper;
import org.displaytag.util.Href;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.tags.RequestContextAwareTag;


public class DisplayTagAuthorizationHelper extends AuthorizationHelper {

	/* (non-Javadoc)
	 * @see org.displaytag.util.AuthorizationHelper#isAuthorizedFor(java.lang.String)
	 */
	@Override
	public boolean isAuthorizedFor(PageContext pageContext, Href colHref) {
        MenuFilterManager menuFilterManager =
        	(MenuFilterManager)WebApplicationContextUtils
        	.getRequiredWebApplicationContext(SpringMvcUtil.getServletContext())
        			.getBean("menuFilterManager");
        
        String url;
        if (colHref.getBaseUrl().startsWith("/")) {
            String contextPath = SpringMvcUtil.getServletContext().getContextPath();
            if (colHref.getBaseUrl().startsWith(contextPath)) {
                url = StringUtils.substringAfter(colHref.getBaseUrl(), contextPath);
            } else {
            	url = colHref.getBaseUrl();
            }
        } else {
        	RequestContext requestContext = getRequestContext(pageContext);
        	HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
        	String currentUri = requestContext.getRequestUri();
        	currentUri = currentUri.substring(0, currentUri.lastIndexOf('/'));
        	currentUri = StringUtils.difference(requestContext.getContextPath(), currentUri);
        	url = currentUri + "/" + colHref.getBaseUrl(); 
        }
	    boolean isAuthorizationDenied = menuFilterManager.disableMenuItem(url);
	    return !isAuthorizationDenied;
	}
	
	private RequestContext getRequestContext(PageContext pageContext) {
		return (RequestContext) pageContext.getAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE);
	}

}
