package com.urbancode.air.plugin.automation;

import com.urbancode.air.*
import org.apache.commons.httpclient.*
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.auth.AuthScope;
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
    HttpClient client
    
    protected def configureWorkspace() {
        HttpMethod workspaceMethod = null
        try {
            workspaceMethod = new GetMethod(url + "subscription")
            def workResult = client.executeMethod(workspaceMethod)
            def workResponse = IO.readText(workspaceMethod.getResponseBodyAsStream())
            def workXml = new XmlParser().parseText(workResponse)
            return workXml.Workspaces.Workspace.findAll{it.'@refObjectName'.equals(workspace) }[0].'@ref'
        }
        finally {
           if(workspaceMethod != null) {
               workspaceMethod.releaseConnection()
           }
        }
    }
    
    protected void setupHttpClient() {
        // create and setup httpClient
        client = new HttpClient()
        client.getParams().setAuthenticationPreemptive(true)
        Credentials defaultcreds = new UsernamePasswordCredentials(user, password)
        client.getState().setCredentials(new AuthScope(base_url, 443), defaultcreds)
        
        // setup proxy if neccessary
        if (proxyHost) {
            out.println("Setting up proxy")
            client.getHostConfiguration().setProxy(proxyHost, Integer.valueOf(proxyPort));
            if (proxyUser && proxyPass) {
                client.getState().setProxyCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(proxyUser, proxyPass));
            }
        }
    }
}