package com.urbancode.air.plugin.automation;

import com.urbancode.air.*
import org.apache.commons.httpclient.*
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.protocol.*
import com.urbancode.commons.util.IO;
import com.urbancode.commons.util.https.OpenSSLProtocolSocketFactory

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() {
        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)
        
        ProtocolSocketFactory socketFactory = new OpenSSLProtocolSocketFactory()
        Protocol https = new Protocol("https", socketFactory, 443)
        Protocol.registerProtocol("https", https)

        // 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));
            }
        }
    }
}