package com.urbancode.air.plugin.automation;

import org.apache.commons.httpclient.*
import org.apache.commons.httpclient.methods.*
import org.apache.commons.httpclient.protocol.*
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.HttpGet

import com.urbancode.air.*
import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder
import com.urbancode.commons.util.IO

public class AutomationBase {
    //**************************************************************************
    // CLASS
    //**************************************************************************

    //**************************************************************************
    // INSTANCE
    //**************************************************************************
    String base_url
    String url
    String user
    String password
    String proxyHost
    String proxyPort
    String proxyPass
    String proxyUser
    String workspace
    String version
    HttpClient client
    
    protected def configureWorkspace() {
        boolean error = false
        HttpGet workspaceMethod = null
        try {
            workspaceMethod = new HttpGet(url + "subscription")
            def workResult = client.execute(workspaceMethod)
            def workResponse = IO.readText(workResult.entity.content)
            def workXml = new XmlParser().parseText(workResponse)
            println workXml
            def workspaceRef = workXml.Workspaces.Workspace.findAll{it.'@refObjectName'.equals(workspace) }[0].'@ref'
            return workspaceRef
        }
        catch (Exception e) {
            println "Either the workspace '${workspace}' does not exist or you do not have access to it. Please check " +
                "the workspace name and confirm that your Rally user account has access to that workspace and then try again."
            error = true
        }
        finally {
           if(workspaceMethod != null) {
               workspaceMethod.releaseConnection()
           }
           
           if (error) {
               System.exit(1)
           }
        }
    }
    
    protected void setupHttpClient() {
        HttpClientBuilder builder = new HttpClientBuilder()
        builder.setTrustAllCerts(true)
        builder.setPreemptiveAuthentication(true)
        builder.setUsername(user)
        builder.setPassword(password)
        
        // setup proxy if neccessary
        if (proxyHost) {
            out.println("Setting up proxy")
            builder.setProxyHost(proxyHost)
            builder.setProxyPort(Integer.valueOf(proxyPort))
            if (proxyUser && proxyPass) {
                builder.setProxyUsername(proxyUser)
                builder.setProxyPassword(proxyPass)
            }
        }
        client = builder.buildClient()
    }
}