package com.apobates.forum.trident.controller.helper;

import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
 * 增强请求对象,RequestTokenParameterFilter需要的输助类
 * 
 * {@link https://www.ocpsoft.org/opensource/how-to-safely-add-modify-servlet-request-parameter-values/}
 * @author xiaofanku
 * @since 20191130
 */
public class EnhancedHttpRequest extends HttpServletRequestWrapper {
	private final Map<String, String[]> modifiableParameters;
	private Map<String, String[]> allParameters = null;

	public EnhancedHttpRequest(HttpServletRequest request) {
		this(request, Collections.EMPTY_MAP);
	}

	public EnhancedHttpRequest(final HttpServletRequest request, final Map<String, String[]> additionalParams) {
		super(request);
		this.modifiableParameters = new TreeMap<String, String[]>();
		this.modifiableParameters.putAll(additionalParams);
	}

	@Override
	public String getParameter(final String name) {
		String[] strings = getParameterMap().get(name);
		if (strings != null) {
			return strings[0];
		}
		return super.getParameter(name);
	}

	@Override
	public Map<String, String[]> getParameterMap() {
		if (null==allParameters) {
			allParameters = new TreeMap<String, String[]>();
			allParameters.putAll(super.getParameterMap());
			allParameters.putAll(modifiableParameters);
		}
		// Return an unmodifiable collection because we need to uphold the
		// interface contract.
		return Collections.unmodifiableMap(allParameters);
	}

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

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