package com.apobates.forum.thrones.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需要的输助类
 *
 * @author xiaofanku
 * @since 20200525
 */
public class EnhancedHttpRequest extends HttpServletRequestWrapper {
    private final Map<String, String[]> modifiableParameters;
    private Map<String, String[]> allParameters = null;
    
    public EnhancedHttpRequest(HttpServletRequest request) {
        this(request, Collections.emptyMap());
    }
    
    public EnhancedHttpRequest(final HttpServletRequest request, final Map<String, String[]> additionalParams) {
        super(request);
        this.modifiableParameters = new TreeMap<>();
        this.modifiableParameters.putAll(additionalParams);
    }
    
    @Override
    public String getParameter(final String name) {
        String[] strings = getParameterMap().get(name);
        if (null != strings) {
            return strings[0];
        }
        return super.getParameter(name);
    }
    
    @Override
    public Map<String, String[]> getParameterMap() {
        if (null == allParameters) {
            allParameters = new TreeMap<>();
            allParameters.putAll(super.getParameterMap());
            allParameters.putAll(modifiableParameters);
        }
        // Return an unmodifiable collection because we need to uphold the
        // interface contract.
        return Map.copyOf(allParameters);
    }
    
    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(getParameterMap().keySet());
    }
    
    @Override
    public String[] getParameterValues(final String name) {
        return getParameterMap().get(name);
    }
}