/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.commons.chain2.web.servlet;


import java.io.BufferedReader;
import java.io.IOException;
import java.security.Principal;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpUpgradeHandler;
import javax.servlet.http.Part;

import org.apache.commons.chain2.web.MockEnumeration;
import org.apache.commons.chain2.web.MockPrincipal;


/**
 *  Mock Object for HttpServletRequest
 */
public final class MockHttpServletRequest implements HttpServletRequest {

    private Map<String, Object> attributes = new HashMap<>();
    private String contextPath = null;
    private Map<String, String[]> headers = new HashMap<>();
    private Cookie[] cookies = {};
    private Locale locale = null;
    private Map<String, String[]> parameters = new HashMap<>();
    private String pathInfo = null;
    private Principal principal = null;
    private String queryString = null;
    private String servletPath = null;
    private HttpSession session = null;

    /**
     * constructor
     */
    public MockHttpServletRequest() {
        super();
    }

    /**
     * @param ses HttpSession
     */
    public MockHttpServletRequest(final HttpSession ses) {
        super();
        setHttpSession(ses);
    }

    /**
     * @param context String
     * @param servlet String
     * @param info String
     * @param query String
     */
    public MockHttpServletRequest(final String context, final String servlet,
            final String info, final String query) {
        super();
        setPathElements(context, servlet, info, query);
    }

    /**
     * @param context String
     * @param servlet String
     * @param info String
     * @param query String
     * @param ses HttpSession
     */
    public MockHttpServletRequest(final String context, final String servlet,
            final String info, final String query, final HttpSession ses) {
        super();
        setPathElements(context, servlet, info, query);
        setHttpSession(ses);
    }

    // --------------------------------------------------------- Public Methods

    /**
     * @param name String
     * @param value String
     */
    public void addHeader(final String name, final String value) {
        String[] values = this.headers.get(name);
        if (values == null) {
            String[] results = {value};
            this.headers.put(name, results);
            return;
        }
        String[] results = new String[values.length + 1];
        System.arraycopy(values, 0, results, 0, values.length);
        results[values.length] = value;
        this.headers.put(name, results);
    }

    /**
     * @param name String
     * @param value String
     */
    public void addParameter(final String name, final String value) {
        String[] values = this.parameters.get(name);
        if (values == null) {
            String[] results = {value};
            this.parameters.put(name, results);
            return;
        }
        String[] results = new String[values.length + 1];
        System.arraycopy(values, 0, results, 0, values.length);
        results[values.length] = value;
        this.parameters.put(name, results);
    }

    /**
     * @param name String
     * @param value String
     */
    public void addCookie(final String name, final String value) {
        addCookie(new Cookie(name, value));
    }

    /**
     * @param cookie Cookie
     */
    public void addCookie(final Cookie cookie) {
        Cookie[] newValues = new Cookie[this.cookies.length + 1];
        System.arraycopy(this.cookies, 0, newValues, 0, this.cookies.length);
        this.cookies = newValues;
        this.cookies[this.cookies.length - 1] = cookie;
    }

    /**
     * @param ses HttpSession
     */
    public void setHttpSession(final HttpSession ses) {
        this.session = ses;
    }

    /**
     * @param val Locale
     */
    public void setLocale(final Locale val) {
        this.locale = val;
    }

    /**
     * @param context String
     * @param servlet String
     * @param info String
     * @param query String
     */
    public void setPathElements(final String context, final String servlet,
            final String info, final String query) {

        this.contextPath = context;
        this.servletPath = servlet;
        this.pathInfo = info;
        this.queryString = query;

    }

    /**
     * @param val Principal
     */
    public void setUserPrincipal(final Principal val) {
        this.principal = val;
    }

    // --------------------------------------------- HttpServletRequest Methods

    /**
     * @see javax.servlet.http.HttpServletRequest#getAuthType()
     */
    @Override
    public String getAuthType() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getContextPath()
     */
    @Override
    public String getContextPath() {
        return this.contextPath;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getCookies()
     */
    @Override
    public Cookie[] getCookies() {
        return this.cookies.clone();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getDateHeader(java.lang.String)
     */
    @Override
    public long getDateHeader(final String name) {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getHeader(java.lang.String)
     */
    @Override
    public String getHeader(final String name) {
        String[] values = this.headers.get(name);
        if (values != null) {
            return values[0];
        }
        return null;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getHeaderNames()
     */
    @Override
    public Enumeration<String> getHeaderNames() {
        return new MockEnumeration<>(this.headers.keySet().iterator());
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getHeaders(java.lang.String)
     */
    @Override
    public Enumeration<String> getHeaders(final String name) {
        String[] header = this.headers.get(name);
        if (header == null) {
            header = new String[0];
        }
        return new MockEnumeration<>(Arrays.asList(header).iterator());
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getIntHeader(java.lang.String)
     */
    @Override
    public int getIntHeader(final String name) {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getMethod()
     */
    @Override
    public String getMethod() {
        throw new UnsupportedOperationException();
    }

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

    /**
     * @see javax.servlet.http.HttpServletRequest#getPathTranslated()
     */
    @Override
    public String getPathTranslated() {
        throw new UnsupportedOperationException();
    }

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

    /**
     * @see javax.servlet.http.HttpServletRequest#getRemoteUser()
     */
    @Override
    public String getRemoteUser() {
        if (this.principal != null) {
            return this.principal.getName();
        }
        return null;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getRequestedSessionId()
     */
    @Override
    public String getRequestedSessionId() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getRequestURI()
     */
    @Override
    public String getRequestURI() {
        StringBuilder sb = new StringBuilder();
        if (this.contextPath != null) {
            sb.append(this.contextPath);
        }
        if (this.servletPath != null) {
            sb.append(this.servletPath);
        }
        if (this.pathInfo != null) {
            sb.append(this.pathInfo);
        }
        if (sb.length() > 0) {
            return sb.toString();
        }
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getRequestURL()
     */
    @Override
    public StringBuffer getRequestURL() {
        throw new UnsupportedOperationException();
    }

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

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

    /**
     * @see javax.servlet.http.HttpServletRequest#getSession(boolean)
     */
    @Override
    public HttpSession getSession(final boolean create) {
        if (create && this.session == null) {
            throw new UnsupportedOperationException();
        }
        return this.session;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getUserPrincipal()
     */
    @Override
    public Principal getUserPrincipal() {
        return this.principal;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromCookie()
     */
    @Override
    public boolean isRequestedSessionIdFromCookie() {
        throw new UnsupportedOperationException();
    }

    /**
     * @deprecated deprecated
     */
    @Deprecated
    @Override
    public boolean isRequestedSessionIdFromUrl() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromURL()
     */
    @Override
    public boolean isRequestedSessionIdFromURL() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid()
     */
    @Override
    public boolean isRequestedSessionIdValid() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#isUserInRole(java.lang.String)
     */
    @Override
    public boolean isUserInRole(final String role) {
        if (this.principal instanceof MockPrincipal) {
            return ((MockPrincipal) this.principal).isUserInRole(role);
        }
        return false;
    }


    // ------------------------------------------------- ServletRequest Methods

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

    /**
     * @see javax.servlet.ServletRequest#getAttributeNames()
     */
    @Override
    public Enumeration<String> getAttributeNames() {
        return new MockEnumeration<>(this.attributes.keySet().iterator());
    }

    /**
     * @see javax.servlet.ServletRequest#getCharacterEncoding()
     */
    @Override
    public String getCharacterEncoding() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getContentLength()
     */
    @Override
    public int getContentLength() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getContentType()
     */
    @Override
    public String getContentType() {
        throw new UnsupportedOperationException();
    }

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

    /**
     * @see javax.servlet.ServletRequest#getLocale()
     */
    @Override
    public Locale getLocale() {
        return this.locale;
    }

    /**
     * @see javax.servlet.ServletRequest#getLocales()
     */
    @Override
    public Enumeration<Locale> getLocales() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getLocalAddr()
     */
    @Override
    public String getLocalAddr() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getLocalName()
     */
    @Override
    public String getLocalName() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getLocalPort()
     */
    @Override
    public int getLocalPort() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getParameter(java.lang.String)
     */
    @Override
    public String getParameter(final String name) {
        String[] values = this.parameters.get(name);
        if (values != null) {
            return values[0];
        }
        return null;
    }

    /**
     * @see javax.servlet.ServletRequest#getParameterMap()
     */
    @Override
    public Map<String, String[]> getParameterMap() {
        return this.parameters;
    }

    /**
     * @see javax.servlet.ServletRequest#getParameterNames()
     */
    @Override
    public Enumeration<String> getParameterNames() {
        return new MockEnumeration<>(this.parameters.keySet().iterator());
    }

    /**
     * @see javax.servlet.ServletRequest#getParameterValues(java.lang.String)
     */
    @Override
    public String[] getParameterValues(final String name) {
        return this.parameters.get(name);
    }

    /**
     * @see javax.servlet.ServletRequest#getProtocol()
     */
    @Override
    public String getProtocol() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getReader()
     */
    @Override
    public BufferedReader getReader() {
        throw new UnsupportedOperationException();
    }

    /**
     * @deprecated deprecated
     */
    @Deprecated
    @Override
    public String getRealPath(final String path) {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getRemoteAddr()
     */
    @Override
    public String getRemoteAddr() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getRemoteHost()
     */
    @Override
    public String getRemoteHost() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getRemotePort()
     */
    @Override
    public int getRemotePort() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getRequestDispatcher(java.lang.String)
     */
    @Override
    public RequestDispatcher getRequestDispatcher(final String path) {
        throw new UnsupportedOperationException();
    }

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

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

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

    /**
     * @see javax.servlet.ServletRequest#isSecure()
     */
    @Override
    public boolean isSecure() {
        return false;
    }

    /**
     * @see javax.servlet.ServletRequest#removeAttribute(java.lang.String)
     */
    @Override
    public void removeAttribute(final String name) {
        this.attributes.remove(name);
    }

    /**
     * @see javax.servlet.ServletRequest#setAttribute(java.lang.String, java.lang.Object)
     */
    @Override
    public void setAttribute(final String name, final Object value) {
        if (value == null) {
            this.attributes.remove(name);
        } else {
            this.attributes.put(name, value);
        }
    }

    /**
     * @see javax.servlet.ServletRequest#setCharacterEncoding(java.lang.String)
     */
    @Override
    public void setCharacterEncoding(final String name) {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getAsyncContext()
     */
    @Override
    public AsyncContext getAsyncContext() {
        return null;
    }

    /**
     * @see javax.servlet.ServletRequest#getDispatcherType()
     */
    @Override
    public DispatcherType getDispatcherType() {
        return null;
    }

    /**
     * @see javax.servlet.ServletRequest#getServletContext()
     */
    @Override
    public ServletContext getServletContext() {
        return null;
    }

    /**
     * @see javax.servlet.ServletRequest#isAsyncStarted()
     */
    @Override
    public boolean isAsyncStarted() {
        return false;
    }

    /**
     * @see javax.servlet.ServletRequest#isAsyncSupported()
     */
    @Override
    public boolean isAsyncSupported() {
        return false;
    }

    /**
     * @see javax.servlet.ServletRequest#startAsync()
     */
    @Override
    public AsyncContext startAsync() {
        return null;
    }

    /**
     * @see javax.servlet.ServletRequest#startAsync(
     * javax.servlet.ServletRequest, javax.servlet.ServletResponse)
     */
    @Override
    public AsyncContext startAsync(final ServletRequest arg0, final ServletResponse arg1) {
        return null;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest
     * #authenticate(javax.servlet.http.HttpServletResponse)
     */
    @Override
    public boolean authenticate(final HttpServletResponse arg0) throws IOException,
            ServletException {
        return false;
    }


    /**
     * @see javax.servlet.http.HttpServletRequest#getPart(java.lang.String)
     */
    @Override
    public Part getPart(final String arg0)
            throws IOException, IllegalStateException, ServletException {
        return null;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getParts()
     */
    @Override
    public Collection<Part> getParts() throws IOException,
            IllegalStateException, ServletException {
        return null;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#login(java.lang.String, java.lang.String)
     */
    @Override
    public void login(final String arg0, final String arg1) throws ServletException {
        return;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#logout()
     */
    @Override
    public void logout() throws ServletException {
        return;
    }

    /**
     * @see javax.servlet.ServletRequest#getContentLengthLong()
     */
    @Override
    public long getContentLengthLong() {
        return 0;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#changeSessionId()
     */
    @Override
    public String changeSessionId() {
        return null;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#upgrade(java.lang.Class)
     */
    @Override
    public <T extends HttpUpgradeHandler> T upgrade(final Class<T> arg0)
            throws IOException, ServletException {
        return null;
    }

}
