package com.myeclipseide.progfilter;

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

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

@WebFilter("/*")
public class NumberRemoverFilter implements Filter {

	private ServletContext servletContext;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

		servletContext = filterConfig.getServletContext();

		servletContext.log("NumberRemoverFilter initialized");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		final Map<String, String[]> filteredParams = Collections
				.unmodifiableMap(removeNumbersAndSpecialChars(request
						.getParameterMap()));

		HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(
				(HttpServletRequest) request) {
			@Override
			public Map<String, String[]> getParameterMap() {
				return filteredParams;
			}

			@Override
			public String getParameter(String name) {
				return filteredParams.get(name) == null ? null : filteredParams
						.get(name)[0];
			}

			@Override
			public Enumeration<String> getParameterNames() {
				return Collections.enumeration(filteredParams.keySet());
			}

			@Override
			public String[] getParameterValues(String name) {
				return filteredParams.get(name);
			}
		};

		try {
			servletContext.log("NumberRomoverFilter invoking filter chain...");

			chain.doFilter(wrappedRequest, response);

		} finally {

			servletContext.log("NumberRomoverFilter done filtering request");
		}
	}

	/**
	 * Performs the vowel removal work of this filter.
	 * 
	 * @param parameterMap
	 *            the map of parameter names and values in the original request.
	 * @return A copy of the original map with all the same keys, but whose
	 *         values do not contain vowels.
	 */
	private Map<String, String[]> removeNumbersAndSpecialChars(
			Map<String, String[]> parameterMap) {
		Map<String, String[]> m = new HashMap<String, String[]>();
		for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
			String[] orig = entry.getValue();
			String[] numless = new String[orig.length];
			for (int i = 0; i < orig.length; i++) {
				numless[i] = orig[i].replaceAll("[0-9&$!*%#@]", "");
			}
			m.put(entry.getKey(), numless);

		}
		return m;
	}

	@Override
	public void destroy() {
		servletContext.log("NumberRemoverFilter destroyed");
		servletContext = null;
	}

}
