package com.uas.platform.b2b.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

/**
 * 资源数据定义，将所有的资源和权限对应关系建立起来，即定义某一资源可以被哪些角色访问
 * 
 * @author yingp
 * @version 1.0
 */
public class CustomSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

	/**
	 * LOGGER 日志对象
	 */
	private final static Logger LOGGER = Logger.getLogger(CustomSecurityMetadataSource.class);

	private HashMap<String, Collection<ConfigAttribute>> map = new HashMap<String, Collection<ConfigAttribute>>();

	/**
	 * 加载资源，初始化资源变量
	 * 
	 */
	private void loadResourceDefine() {
		Collection<ConfigAttribute> array = new ArrayList<ConfigAttribute>(4);
		ConfigAttribute cfg = new SecurityConfig("ROLE_USER");
		array.add(cfg);
		map.put("/**", array);
	}

	public CustomSecurityMetadataSource() {
		loadResourceDefine();
	}

	/**
	 * 根据路径获取访问权限的集合接口
	 * 
	 * @param object
	 * @return
	 * @throws IllegalArgumentException
	 */
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

		LOGGER.info(object);

		HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();

		RequestMatcher matcher = null;
		String resUrl = null;
		for (Iterator<String> iter = map.keySet().iterator(); iter.hasNext();) {
			resUrl = iter.next();
			matcher = new AntPathRequestMatcher(resUrl);
			if (null != resUrl && matcher.matches(request)) {
				return map.get(resUrl);
			}
		}

		return null;
	}

	/**
	 * @return
	 */
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	/**
	 * @param clazz
	 * @return
	 */
	public boolean supports(Class<?> clazz) {
		return true;
	}

}
