package org.seasar.extension.mock.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.seasar.framework.util.EmptyEnumeration;
import org.seasar.framework.util.EnumerationAdapter;

/**
 * @author higa
 *  
 */
public class MockHttpServletRequest implements HttpServletRequest {

	private static SimpleDateFormat[] DATE_FORMATTERS = {
			new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US),
			new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US),
			new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US),
			new SimpleDateFormat("yyyy-MM-dd"),
			new SimpleDateFormat("yyyy/MM/dd") };

	private ServletContext servletContext_;

	private String servletPath_;

	private String authType_;

	private List cookieList = new ArrayList();

	private Map headers_ = new HashMap();

	private String method_ = "POST";

	private String pathInfo_;

	private String pathTranslated_;

	private String queryString_;

	private MockHttpSession session_;

	private String scheme_ = "http";

	private int serverPort_ = 80;

	private String protocol_ = "HTTP/1.1";

	private String serverName_ = "localhost";

	private Map attributes_ = new HashMap();

	private String characterEncoding_ = "ISO-8859-1";

	private int contentLength_;

	private String contentType_;

	public MockHttpServletRequest(ServletContext servletContext,
			String servletPath) {

		servletContext_ = servletContext;
		if (servletPath.charAt(0) == '/') {
			servletPath_ = servletPath;
		} else {
			servletPath_ = "/" + servletPath;
		}
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getAuthType()
	 */
	public String getAuthType() {
		return authType_;
	}

	public void setAuthType(String authType) {
		authType_ = authType;
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getCookies()
	 */
	public Cookie[] getCookies() {
		return (Cookie[]) cookieList.toArray(new Cookie[cookieList.size()]);
	}

	public void addCookie(Cookie cookie) {
		cookieList.add(cookie);
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getDateHeader(java.lang.String)
	 */
	public long getDateHeader(String name) {
		String value = getHeader(name);
		if (value == null) {
			return -1L;
		}
		for (int i = 0; i < DATE_FORMATTERS.length; i++) {
			try {
				return DATE_FORMATTERS[i].parse(value).getTime();
			} catch (ParseException ignore) {
			}
		}
		throw new IllegalArgumentException(name);
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getHeader(java.lang.String)
	 */
	public String getHeader(String name) {
		List values = getHeaderList(name);
		if (values != null) {
			return (String) values.get(0);
		} else {
			return null;
		}
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getHeaders(java.lang.String)
	 */
	public Enumeration getHeaders(String name) {
		List values = getHeaderList(name);
		if (values != null) {
			return new EnumerationAdapter(values.iterator());
		} else {
			return new EmptyEnumeration();
		}
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getHeaderNames()
	 */
	public Enumeration getHeaderNames() {
		return new EnumerationAdapter(headers_.keySet().iterator());
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getIntHeader(java.lang.String)
	 */
	public int getIntHeader(String name) {
		String value = getHeader(name);
		if (value == null) {
			return -1;
		} else {
			return Integer.parseInt(value);
		}
	}

	public void addHeader(String name, String value) {
		List values = getHeaderList(name);
		if (values == null) {
			values = new ArrayList();
		}
		values.add(value);
		headers_.put(name.toLowerCase(), values);
	}

	public void addDateHeader(String name, long value) {
		addHeader(name, DATE_FORMATTERS[0].format(new Date(value)));
	}

	public void addIntHeader(String name, int value) {
		addHeader(name, "" + value);
	}

	private List getHeaderList(String name) {
		name = name.toLowerCase();
		return (List) headers_.get(name);
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getMethod()
	 */
	public String getMethod() {
		return method_;
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getPathInfo()
	 */
	public String getPathInfo() {
		return pathInfo_;
	}

	public void setPathInfo(String pathInfo) {
		pathInfo_ = pathInfo;
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getPathTranslated()
	 */
	public String getPathTranslated() {
		return pathTranslated_;
	}

	public void setPathTranslated(String pathTranslated) {
		pathTranslated_ = pathTranslated;
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getContextPath()
	 */
	public String getContextPath() {
		return servletContext_.getServletContextName();
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getQueryString()
	 */
	public String getQueryString() {
		return queryString_;
	}

	public void setQueryString(String queryString) {
		queryString_ = queryString;
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getRemoteUser()
	 */
	public String getRemoteUser() {
		return System.getProperty("user.name");
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#isUserInRole(java.lang.String)
	 */
	public boolean isUserInRole(String arg0) {
		throw new UnsupportedOperationException();
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getUserPrincipal()
	 */
	public Principal getUserPrincipal() {
		throw new UnsupportedOperationException();
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getRequestedSessionId()
	 */
	public String getRequestedSessionId() {
		if (session_ != null) {
			return session_.getId();
		} else {
			return null;
		}
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getRequestURI()
	 */
	public String getRequestURI() {
		String contextPath = getContextPath();
		if (contextPath.equals("/")) {
			return servletPath_;
		}
		return contextPath + servletPath_;
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getRequestURL()
	 */
	public StringBuffer getRequestURL() {
		StringBuffer url = new StringBuffer();
		url.append(scheme_);
		url.append("://");
		url.append(serverName_);
		if ((scheme_.equals("http") && (serverPort_ != 80))
				|| (scheme_.equals("https") && (serverPort_ != 443))) {

			url.append(':');
			url.append(serverPort_);
		}
		url.append(getRequestURI());
		return url;
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getServletPath()
	 */
	public String getServletPath() {
		return servletPath_;
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getSession(boolean)
	 */
	public HttpSession getSession(boolean create) {
		if (session_ != null) {
			return session_;
		}
		if (create) {
			session_ = new MockHttpSession(servletContext_);
		}
		if (session_ != null) {
			session_.access();
		}
		return session_;
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#getSession()
	 */
	public HttpSession getSession() {
		return getSession(true);
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid()
	 */
	public boolean isRequestedSessionIdValid() {
		if (session_ != null) {
			return session_.isValid();
		}
		return false;
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromCookie()
	 */
	public boolean isRequestedSessionIdFromCookie() {
		return session_ != null;
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromURL()
	 */
	public boolean isRequestedSessionIdFromURL() {
		return false;
	}

	/**
	 * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromUrl()
	 */
	public boolean isRequestedSessionIdFromUrl() {
		return isRequestedSessionIdFromURL();
	}

	/**
	 * @see javax.servlet.ServletRequest#getAttribute(java.lang.String)
	 */
	public Object getAttribute(String name) {
		return attributes_.get(name);
	}

	/**
	 * @see javax.servlet.ServletRequest#getAttributeNames()
	 */
	public Enumeration getAttributeNames() {
		return new EnumerationAdapter(attributes_.keySet().iterator());
	}

	/**
	 * @see javax.servlet.ServletRequest#getCharacterEncoding()
	 */
	public String getCharacterEncoding() {
		return characterEncoding_;
	}

	/**
	 * @see javax.servlet.ServletRequest#setCharacterEncoding(java.lang.String)
	 */
	public void setCharacterEncoding(String characterEncoding)
			throws UnsupportedEncodingException {

		characterEncoding_ = characterEncoding;
	}

	/**
	 * @see javax.servlet.ServletRequest#getContentLength()
	 */
	public int getContentLength() {
		return contentLength_;
	}

	public void setContentLength(int contentLength) {
		contentLength_ = contentLength;
	}

	/**
	 * @see javax.servlet.ServletRequest#getContentType()
	 */
	public String getContentType() {
		return contentType_;
	}

	public void setContentType(String contentType) {
		contentType_ = contentType;
	}

	/**
	 * @see javax.servlet.ServletRequest#getInputStream()
	 */
	public ServletInputStream getInputStream() throws IOException {
		throw new UnsupportedOperationException();
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see javax.servlet.ServletRequest#getParameter(java.lang.String)
	 */
	public String getParameter(String arg0) {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see javax.servlet.ServletRequest#getParameterNames()
	 */
	public Enumeration getParameterNames() {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see javax.servlet.ServletRequest#getParameterValues(java.lang.String)
	 */
	public String[] getParameterValues(String arg0) {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see javax.servlet.ServletRequest#getParameterMap()
	 */
	public Map getParameterMap() {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	/**
	 * @see javax.servlet.ServletRequest#getProtocol()
	 */
	public String getProtocol() {
		return protocol_;
	}

	public void setProtocol(String protocol) {
		protocol_ = protocol;
	}

	/**
	 * @see javax.servlet.ServletRequest#getScheme()
	 */
	public String getScheme() {
		return scheme_;
	}

	public void setScheme(String scheme) {
		scheme_ = scheme;
	}

	/**
	 * @see javax.servlet.ServletRequest#getServerName()
	 */
	public String getServerName() {
		return serverName_;
	}

	public void setServerName(String serverName) {
		serverName_ = serverName;
	}

	/**
	 * @see javax.servlet.ServletRequest#getServerPort()
	 */
	public int getServerPort() {
		return serverPort_;
	}

	public void setServerPort(int serverPort) {
		serverPort_ = serverPort;
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see javax.servlet.ServletRequest#getReader()
	 */
	public BufferedReader getReader() throws IOException {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see javax.servlet.ServletRequest#getRemoteAddr()
	 */
	public String getRemoteAddr() {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see javax.servlet.ServletRequest#getRemoteHost()
	 */
	public String getRemoteHost() {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see javax.servlet.ServletRequest#setAttribute(java.lang.String,
	 *      java.lang.Object)
	 */
	public void setAttribute(String arg0, Object arg1) {
		// TODO 自動生成されたメソッド・スタブ

	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see javax.servlet.ServletRequest#removeAttribute(java.lang.String)
	 */
	public void removeAttribute(String arg0) {
		// TODO 自動生成されたメソッド・スタブ

	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see javax.servlet.ServletRequest#getLocale()
	 */
	public Locale getLocale() {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see javax.servlet.ServletRequest#getLocales()
	 */
	public Enumeration getLocales() {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see javax.servlet.ServletRequest#isSecure()
	 */
	public boolean isSecure() {
		// TODO 自動生成されたメソッド・スタブ
		return false;
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see javax.servlet.ServletRequest#getRequestDispatcher(java.lang.String)
	 */
	public RequestDispatcher getRequestDispatcher(String arg0) {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	/*
	 * (非 Javadoc)
	 * 
	 * @see javax.servlet.ServletRequest#getRealPath(java.lang.String)
	 */
	public String getRealPath(String arg0) {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

}