package com.app.framework.core.api.request;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * Api的HttpServletRequest，主要是完成如下功能：
 * 因API要求不直接传递用户信息，而是传递一个token用于身份认证。故通过重写request参数将认证后的用户信息传入请求的方法中，认证失败则直接返回401代码的错误
 * 
 */
@SuppressWarnings({"unchecked"})
public class ApiHttpServletRequest extends HttpServletRequestWrapper {
	private static final String MEMBER_ID = "apiLoginUserId";

	private Long apiLoginUserId = null;
	
	public ApiHttpServletRequest(HttpServletRequest request) {
		super(request);
	}
	public ApiHttpServletRequest(HttpServletRequest request, Long apiLoginUserId) {
		super(request);
		this.apiLoginUserId = apiLoginUserId;
	}

	@Override
	public String getParameter(String name) {
		String value = super.getParameter(name);
		if (value == null && MEMBER_ID.equals(name) && apiLoginUserId != null) {
			value = apiLoginUserId.toString();
		}
		return value;
	}

	@Override
	public Map getParameterMap() {
		Map map = super.getParameterMap();
		if (!map.containsKey(MEMBER_ID) && apiLoginUserId != null) {
			map = new HashMap(map);
			map.put(MEMBER_ID, apiLoginUserId.toString());
		}
		return map;
	}

	@Override
	public Enumeration getParameterNames() {
		if (super.getParameter(MEMBER_ID) == null && apiLoginUserId != null) {
			return Collections.enumeration(getParameterMap().keySet());
		} else {
			return super.getParameterNames();
		}
	}

	@Override
	public String[] getParameterValues(String name) {
		String[] values = super.getParameterValues(name);
		if (values == null && MEMBER_ID.equals(name) && apiLoginUserId != null) {
			values = new String[]{apiLoginUserId.toString()};
		}
		return values;
	}
}