package org.fouram.core.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 静态文件缓存Filter
 * @author Liup
 */
public class StaticCacheFilter implements Filter {
	private FilterConfig config = null;

	private HashMap<String, Integer> expiresMap = new HashMap<>();

	public void init(FilterConfig filterConfig) {
		this.config = filterConfig;
		expiresMap.clear();
		Enumeration<String> names = config.getInitParameterNames();
		while (names.hasMoreElements()) {
			try {
				String name = (String) names.nextElement();
				String value = config.getInitParameter(name);
				Integer expire = Integer.valueOf(value);
				expiresMap.put(name, expire);
			} catch (Exception ex) {
			}
		}
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String uri = req.getRequestURI();
		String ext = null;
		int dot = uri.lastIndexOf(".");
		if (dot != -1) {
			ext = uri.substring(dot + 1);
		}
		setResponseHeader(res, uri, ext);
		chain.doFilter(request, response);
	}

	public void destroy() {
	}

	protected FilterConfig getFilterConfig() {
		return (config);
	}

	private void setResponseHeader(HttpServletResponse response, String uri, String ext) {
		if (ext != null && ext.length() > 0) {
			Integer expires = (Integer) expiresMap.get(ext.toLowerCase());
			if (expires != null) {
				if (expires.intValue() > 0) {
					response.setHeader("Cache-Control", "max-age=" + expires.intValue());
				} else {
					response.setHeader("Cache-Control", "no-cache");
					response.setHeader("Pragma", "no-cache");
					response.setDateHeader("Expires", 0);
				}
			}
		}
	}
}