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


import it.mice.voila.runtime.security.ReloadableMethodSecurityMetadataSource;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.util.AntPathRequestMatcher;
import org.springframework.security.web.util.RequestMatcher;

public class FilterChainProxyPostProcessor implements BeanPostProcessor {
	protected static Log logger = LogFactory
			.getLog(ReloadableMethodSecurityMetadataSource.class);

	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if (bean instanceof FilterChainProxy) {
			if (logger.isDebugEnabled()) {
				logger.debug("Post-processing bean: " + beanName);
			}
			FilterChainProxy filterChainProxy = (FilterChainProxy)bean;
			//UrlMatcher urlMatcher = filterChainProxy.getMatcher();
			Map<RequestMatcher, List<Filter>> filterChainMap = (Map<RequestMatcher, List<Filter>>)filterChainProxy.getFilterChainMap();
			Map<RequestMatcher, List<Filter>> filterChainMapNew = new LinkedHashMap<RequestMatcher, List<Filter>>();
			ArrayList<Filter> emptyFilter = new ArrayList<Filter>();
			filterChainMapNew.put(new AntPathRequestMatcher("/resources/**"), emptyFilter);
			filterChainMapNew.put(new AntPathRequestMatcher("/**/*.gif"), emptyFilter);
			filterChainMapNew.put(new AntPathRequestMatcher("/**/*.png"), emptyFilter);
			filterChainMapNew.put(new AntPathRequestMatcher("/**/*.css"), emptyFilter);
			filterChainMapNew.put(new AntPathRequestMatcher("/**/*.js"), emptyFilter);
			filterChainMapNew.put(new AntPathRequestMatcher("/**/*.jpg"), emptyFilter);
			filterChainMapNew.putAll(filterChainMap);
			filterChainProxy.setFilterChainMap(filterChainMapNew);
		}
		return bean;
	}
}
