/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* (c) Copyright IBM Corporation 2015. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
import com.urbancode.air.CommandHelper
import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder
import org.apache.http.client.HttpClient
import org.codehaus.jettison.json.JSONObject

class HelperBase {
    def workDir
    def javaFile
    def udClientJarFile

    def CommandHelper cmdHelper

    def url
    def user
    def password
    def ucdAuthToken

    def HttpClient client

    public void addCredentials(def command) {
        if (ucdAuthToken) {
            command << "--authtoken" << ucdAuthToken
        }
        else {
            command << "--username" << user << "--password" << password
        }
    }

    public CommandHelper getCommandHelper() {
        if (!cmdHelper) {
            cmdHelper = new CommandHelper(workDir)
        }
        return cmdHelper
    }

    public HttpClient getHttpClient() {
        if (!client) {
            def httpUser = user
            def httpPassword = password
            if (ucdAuthToken) {
                httpUser = "PasswordIsAuthToken"

                JSONObject tokenJson = new JSONObject()
                tokenJson.put("token", ucdAuthToken)
                httpPassword = tokenJson.toString()
            }

            HttpClientBuilder clientBuilder = new HttpClientBuilder()
            clientBuilder.setTrustAllCerts(true)
            clientBuilder.setUsername(httpUser)
            clientBuilder.setPassword(httpPassword)
            client = clientBuilder.buildClient()
        }
        return client
    }
}
