package com.ylcm.sys.filter;

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import com.ylcm.sys.common.RequestUtil;


public class ParameterRequestWrapper extends HttpServletRequestWrapper {

	@SuppressWarnings("rawtypes")
	private Map params;

	@SuppressWarnings("rawtypes")
	public ParameterRequestWrapper(HttpServletRequest request, Map newParams) {
		super(request);
		this.params = newParams;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Map getParameterMap() {
		return params;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Enumeration getParameterNames() {
		Vector l = new Vector(params.keySet());
		return l.elements();
	}

	@Override
	public String[] getParameterValues(String name) {
		if (name == null) {
			return null;
		}
		
		Object v = params.get(name);
		if (v == null) {
			return null;
		} else if (v instanceof String[]) {
			return (String[]) v;
		} else if (v instanceof String) {
			return new String[] { (String) v };
		} else {
			return new String[] { v.toString() };
		}
	}

	@Override
	public String getParameter(String name) {
		Object v = params.get(name);
		if (v == null) {
			return null;
		} else if (v instanceof String[]) {
			String[] strArr = (String[]) v;
			if (strArr.length > 0) {
				return strArr[0];
			} else {
				return null;
			}
		} else if (v instanceof String) {
			return (String) v;
		} else {
			return v.toString();
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void mergeParameters(String path) {

		String[] queryParams = path.split("\\?");
		String queryParamString = null;
		if (queryParams.length > 1) {
			queryParamString = queryParams[1];
		}

		if ((queryParamString == null) || (queryParamString.length() < 1))
			return;

		HashMap queryParameters = new HashMap();

		String encoding = getCharacterEncoding();

		if (encoding == null)

			encoding = "UTF-8";

		try {

			RequestUtil.parseParameters(queryParameters, queryParamString,
					encoding);

		} catch (Exception e) {

		}

		params.putAll(queryParameters);
	}

	@Override
	public RequestDispatcher getRequestDispatcher(final String path) {
		final RequestDispatcher dispatcher = super.getRequestDispatcher(path);

		return new RequestDispatcher() {

			public void forward(ServletRequest request, ServletResponse response)
					throws ServletException, IOException {
				mergeParameters(path);
				dispatcher.forward(request, response);
			}

			public void include(ServletRequest request, ServletResponse response)
					throws ServletException, IOException {
				mergeParameters(path);
				dispatcher.include(request, response);
			}
		};
	}

	
	
	
}
