package gov.va.med.mpn.auth.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

/**
 * The Class CustomServletRequestWrapper. This class extends
 * HttpServletReqestWrapper to allow custom attributes to be
 * added to the request header.
 * <p>
 * <A HREF="http://www.hp.com"> Hewlett-Packard Enterprise Services</A>
 * </p>
 * 
 * @author <a href="mailto:david.aar.lucas@hp.com">Aaron Lucas</a>
 * 
 * @see HttpServletRequestWrapper 
 */
public class CustomServletRequestWrapper extends HttpServletRequestWrapper {

	/** The header map. */
	private Map headerMap;

	/**
	 * Instantiates a new custom servlet request wrapper.
	 *
	 * @param request the request
	 */
	public CustomServletRequestWrapper(HttpServletRequest request) {
		super(request);
		headerMap = new HashMap();
	}

	/**
	 * Adds the header.
	 *
	 * @param name the name
	 * @param value the value
	 */
	public void addHeader(String name, String value) {
		headerMap.put(name, new String(value));
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServletRequestWrapper#getHeaderNames()
	 */
	public Enumeration getHeaderNames() {
		HttpServletRequest request = (HttpServletRequest) getRequest();
		List list = new ArrayList();
		for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
			list.add(e.nextElement().toString());
		}

		for (Iterator i = headerMap.keySet().iterator(); i.hasNext();) {
			list.add(i.next());
		}
		return Collections.enumeration(list);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServletRequestWrapper#getHeaders(java.lang.String)
	 */
	@Override
	public Enumeration getHeaders(String name) {
		Enumeration e = super.getHeaders(name);
		if (e != null && e.hasMoreElements()) {
			return e;
		} else {
			List l = new ArrayList();
			if (headerMap.get(name) != null) {
				l.add(headerMap.get(name));
			}
			return Collections.enumeration(l);
		}
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServletRequestWrapper#getHeader(java.lang.String)
	 */
	public String getHeader(String name) {
		Object value;
		if ((value = headerMap.get("" + name)) != null)
			return value.toString();
		else
			return ((HttpServletRequest) getRequest()).getHeader(name);
	}

}
