/**
 *
 * 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 io.hawt.web;

import io.hawt.util.Strings;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;

/**
 * A helper object to store the proxy location details
 */
public class ProxyDetails {
    private static final transient Logger LOG = LoggerFactory.getLogger(ProxyDetails.class);

    private String stringProxyURL;
    private String hostAndPort;
    private String path = "";
    private String userName;
    private String password;
    private  String host;
    private int port = 80;

    public ProxyDetails(HttpServletRequest httpServletRequest) {
        this(httpServletRequest.getPathInfo());

        // use request params for the user/pwd
        String userParam = httpServletRequest.getParameter("_user");
        if (Strings.isNotBlank(userParam)) {
            userName = userParam;
        }
        String pwdParam = httpServletRequest.getParameter("_pwd");
        if (Strings.isNotBlank(pwdParam)) {
            password = pwdParam;
        }
    }

    public ProxyDetails(String pathInfo) {
        hostAndPort = pathInfo;
        while (hostAndPort.startsWith("/")) {
            hostAndPort = hostAndPort.substring(1);
        }

        // remove user/pwd
        int idx = hostAndPort.indexOf("@");
        if (idx > 0) {
            userName = hostAndPort.substring(0, idx);
            hostAndPort = hostAndPort.substring(idx + 1);

            idx = indexOf(userName, ":", "/");
            if (idx > 0) {
                password = userName.substring(idx + 1);
                userName = userName.substring(0, idx);
            }
        }
        host = hostAndPort;
        idx = indexOf(hostAndPort, ":", "/");
        if (idx > 0) {
            host = hostAndPort.substring(0, idx);
            String portText = hostAndPort.substring(idx + 1);
            idx = portText.indexOf("/");
            if (idx >= 0) {
                path = portText.substring(idx);
                portText = portText.substring(0, idx);
            }

            if (Strings.isNotBlank(portText)) {
                port = Integer.parseInt(portText);
                hostAndPort = host + ":" + port;
            } else {
                hostAndPort = host;
            }
        }
        stringProxyURL = "http://" + hostAndPort + path;


        try {
            // Handle the query string
/*
            if (httpServletRequest.getQueryString() != null) {
                stringProxyURL += "?" + URIUtil.encodeQuery(httpServletRequest.getQueryString());
            }
*/
            if (LOG.isDebugEnabled()) {
                LOG.debug("Proxying to " + stringProxyURL);
            }
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
    }

    /**
     * Returns the lowest index of the given list of values
     */
    protected int indexOf(String text, String... values) {
        int answer = -1;
        for (String value : values) {
            int idx = text.indexOf(value);
            if (idx >= 0) {
                if (answer < 0 || idx < answer) {
                    answer = idx;
                }
            }
        }
        return answer;
    }

    public HttpClient createHttpClient(HttpMethod httpMethodProxyRequest) {
        HttpClient client = new HttpClient();

        if (userName != null) {
            //client.getParams().setAuthenticationPreemptive(true);
            httpMethodProxyRequest.setDoAuthentication(true);

            Credentials defaultcreds = new UsernamePasswordCredentials(userName, password);
            client.getState().setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds);
        }
        return client;
    }

    public String getStringProxyURL() {
        return stringProxyURL;
    }

    public String getProxyHostAndPort() {
        return hostAndPort;
    }

    public String getProxyPath() {
        return path;
    }

    public String getHost() {
        return host;
    }

    public int getPort() {
        return port;
    }

    public String getUserName() {
        return userName;
    }

    public String getPassword() {
        return password;
    }

    public String getHostAndPort() {
        return hostAndPort;
    }

    public String getPath() {
        return path;
    }
}

@@ -1216,16 +1216,119 @@
 Request;
+%0Aimport java.util.Arrays;%0Aimport java.util.Enumeration;%0Aimport java.util.HashSet;%0Aimport java.util.Set;
 %0A%0A/**%0A *
@@ -1715,16 +1715,136 @@
  = 80;%0A%0A
+    private static Set%3CString%3E ignoreHeaderNames = new HashSet%3CString%3E(Arrays.asList(%22_user%22, %22_pwd%22, %22_url%22, %22url%22));%0A%0A
     publ
@@ -2257,32 +2257,32 @@
 nk(pwdParam)) %7B%0A
-
             pass
@@ -2299,32 +2299,815 @@
 Param;%0A        %7D
+%0A%0A        // lets add the query parameters%0A        Enumeration iter = httpServletRequest.getParameterNames();%0A        while (iter.hasMoreElements()) %7B%0A            Object next = iter.nextElement();%0A            if (next instanceof String) %7B%0A                String name = next.toString();%0A                if (!ignoreHeaderNames.contains(name)) %7B%0A                    String%5B%5D values = httpServletRequest.getParameterValues(name);%0A                    for (String value : values) %7B%0A                        String prefix = %22?%22;%0A                        if (stringProxyURL.contains(%22?%22)) %7B%0A                            prefix = %22&%22;%0A                        %7D%0A                        stringProxyURL += prefix + name + %22=%22 + value;%0A                    %7D%0A                %7D%0A            %7D%0A        %7D
 %0A    %7D%0A%0A    publ

fix for broken canonical jmx names when connecting to remote jvm; turns out we were not passing the headers across ;)