package com.atlassian.jira.plugins.dvcs.pageobjects;

import com.atlassian.jira.pageobjects.JiraTestedProduct;
import com.google.common.collect.Maps;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.Map.Entry;

public class RestUrlBuilder
{
    private final JiraTestedProduct jira;

    private final String path;
    private final Map<String, String> params = Maps.newHashMap();
    private String hostname;

    public RestUrlBuilder(String path)
    {
        this.jira = null;
        this.path = path;
    }

    public RestUrlBuilder(JiraTestedProduct jira, String path)
    {
        this.jira = jira;
        this.path = path;
    }

    public RestUrlBuilder add(String name, String value)
    {
        params.put(name, value);
        return this;
    }

    public String build()
    {
        StringBuilder url = new StringBuilder();
        url.append(getBaseUrlFast());
        url.append(path);
        url.append(url.indexOf("?") != -1 ? "&" : "?");
        url.append("os_username=admin&os_password=admin");
        for (Entry<String, String> entry : params.entrySet())
        {
            url.append("&");
            url.append(entry.getKey());
            url.append("=");
            url.append(entry.getValue());
        }
        return url.toString();
    }

    @Override
    public String toString()
    {
        return build();
    }

    /**
     * Fast way to get base url. (assuming it's http://hostname:2990/jira)
     *
     * Note: if {@code jira} has been instantiated then we use it to get the real url.
     *
     * @return
     */
    private String getBaseUrlFast()
    {
        if (jira == null)
        {
            try
            {
                String hostname = InetAddress.getLocalHost().getHostName();
                return "http://" + hostname + ":2990/jira";
            } catch (UnknownHostException e)
            {
                throw new RuntimeException(e);
            }
        } else
        {
            return jira.environmentData().getBaseUrl().toExternalForm();
        }
    }
}

@@ -262,16 +262,538 @@
 Entry;%0A%0A
+/**%0A * Class to assist with constructing urls when querying rest resources during integration tests.%0A * %3Cp/%3E%0A * If the constructor %7B@code RestUrlBuilder(String)%7D is used, then an JIRA base url of %22http://%22 + hostname + %22:2990/jira%22%0A * is assumed, and this is returned from %7B@code getBaseUrlFast()%7D. If the constructor%0A * %7B@code RestUrlBuilder(JiraTestedProduct, String)%7D is used, then the %7B@code JiraTestedProduct%7D is queried to get the%0A * actual base url of the JIRA instance when %7B@code getBaseUrlFast()%7D is called.%0A */%0A
 public c
@@ -859,40 +859,8 @@
 ira;
-%0A%0A    private final String path;
 %0A   
@@ -934,31 +934,33 @@
 private 
+final 
 String 
-hostname
+path
 ;%0A%0A    p

improve javadocs and remove unused member variable.