package com.thoughtworks.webdriver.inprocess;

import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jetty.testing.HttpTester;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class InProcessWebConnection implements WebConnection {
    private HttpAppTester appTester;

    public InProcessWebConnection(WebClient webClient, HttpAppTester appTester) {
        this.appTester = appTester;
    }

    @Override
    public WebResponse getResponse(WebRequest request) throws IOException {

        String rawRequests = generateRawRequest(request);

        String rawResponse;
        try {
            rawResponse = appTester.getResponses(rawRequests);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        final WebResponseData responseData = parseRawResponse(rawResponse);
        return new WebResponse(responseData, request.getUrl(), request.getHttpMethod(), 0);
    }

    private String generateRawRequest(WebRequest request) throws IOException {
        HttpTester httpTester = new HttpTester();
        httpTester.setMethod(request.getHttpMethod().name());
        httpTester.setURI(request.getUrl().toString());
        httpTester.setVersion("HTTP/1.0");
        if (request.getHttpMethod() == HttpMethod.GET) {
        } else if (request.getHttpMethod() == HttpMethod.POST) {
            if (request.getEncodingType() == FormEncodingType.URL_ENCODED) {
                httpTester.setHeader("Content-Type", "application/x-www-form-urlencoded");
                httpTester.setContent(generateFormDataAsString(request));
            }
        }
        return httpTester.generate();
    }

    private WebResponseData parseRawResponse(String rawResponse) throws IOException {
        HttpTester httpTester = new HttpTester();
        httpTester.parse(rawResponse);
        final List<NameValuePair> headers = new ArrayList<NameValuePair>();
        Enumeration headerNames = httpTester.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement().toString();
            Enumeration headerValues = httpTester.getHeaderValues(headerName);
            while (headerValues.hasMoreElements()) {
                headers.add(new NameValuePair(headerName, headerValues.nextElement().toString()));
            }
        }
        String content = httpTester.getContent();
        if (content == null) content = "";
        return new WebResponseData(content.getBytes(httpTester.getCharacterEncoding()), httpTester.getStatus(), httpTester.getReason(), headers);
    }

    private String generateFormDataAsString(WebRequest request) {
        List<NameValuePair> requestParameters = request.getRequestParameters();

        StringBuilder s = new StringBuilder();

        for (NameValuePair requestParameter : requestParameters) {

            String key = requestParameter.getName();

            if (s.length() > 0) {
                s.append('&');
            }
            s.append(urlEncode(key)).append("=");
            String value = requestParameter.getValue();

            if (StringUtils.isNotEmpty(value)) {
                s.append(urlEncode(value));
            }

        }

        return s.toString();
    }

    private String urlEncode(String key) {
        try {
            return URLEncoder.encode(key, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}


@@ -292,32 +292,110 @@
 odingException;%0A
+import java.net.URI;%0Aimport java.net.URISyntaxException;%0Aimport java.net.URL;%0A
 import java.net.
@@ -406,16 +406,16 @@
 ncoder;%0A
-
 import j
@@ -1447,16 +1447,27 @@
 .setURI(
+relativize(
 request.
@@ -1474,26 +1474,16 @@
 getUrl()
-.toString(
 ));%0A    
@@ -1501,88 +1501,39 @@
 ter.
-setVersion(%22HTTP/1.0%22);%0A        if (request.getHttpMethod() == HttpMethod.GET) %7B
+addHeader(%22Host%22, %22localhost%22);
 %0A   
@@ -1541,15 +1541,8 @@
     
-%7D else 
 if (
@@ -1845,32 +1845,32 @@
     %7D%0A        %7D%0A
-
         return h
@@ -1890,32 +1890,688 @@
 erate();%0A    %7D%0A%0A
+    private String relativize(URL absoluteUrl) %7B%0A        try %7B%0A            URI uri = absoluteUrl.toURI();%0A            String path = uri.getPath();%0A            String query = uri.getQuery();%0A            String fragment = uri.getFragment();%0A%0A            StringBuilder sb = new StringBuilder(path);%0A            if (StringUtils.isNotEmpty(query)) %7B%0A                sb.append(%22?%22).append(query);%0A            %7D%0A            if (StringUtils.isNotEmpty(fragment)) %7B%0A                sb.append(%22#%22).append(fragment);%0A            %7D%0A            return sb.toString();%0A        %7D catch (URISyntaxException e) %7B%0A            throw new RuntimeException(e);%0A        %7D%0A%0A    %7D%0A%0A
     private WebR

use HTTP/1.1