/*
 * Licensed Materials - Property of IBM* and/or HCL**
 * UrbanCode Build
 * (c) Copyright IBM Corporation 2013, 2017. All Rights Reserved.
 * (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
 *
 * U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
 * GSA ADP Schedule Contract with IBM Corp.
 *
 * * Trademark of International Business Machines
 * ** Trademark of HCL Technologies Limited
 */
import org.apache.http.HttpResponse
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity

import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder

import com.urbancode.ubuild.ucbtool.UCBTool

public class UCBUtilsHelper {

    //**************************************************************************
    // CLASS
    //**************************************************************************

    //**************************************************************************
    // INSTANCE
    //**************************************************************************

    public UCBUtilsHelper() {
    }

    def addProperties(Properties properties, String scope) {
        def propertiesXml = new java.io.StringWriter()
        def builder = new groovy.xml.MarkupBuilder(propertiesXml)

        builder."properties"() {
            properties.keySet().each { propName ->
                    def propValue = properties.getProperty(propName);
                    "property"(
                        name:propName,
                        propValue
                    )
            }
        }

        if (propertiesXml) {
            UCBTool ucbTool = new UCBTool()
            def id = null;
            if ("buildlife".equals(scope)) {
                id = System.getenv("BUILD_LIFE_ID")
            }
            else if ("job".equals(scope)) {
                id = System.getenv("JOB_ID")
            }
            else if ("buildrequest".equals(scope)) {
                 id = System.getenv("REQUEST_ID")
            }
            else if (!"system".equals(scope)){
                throw new IllegalArgumentException("unknown scope $scope");
             }

            String baseUrl = System.getenv("WEB_URL")
            def authToken = System.getenv("AUTH_TOKEN")
            ucbTool.addProperties(baseUrl, authToken, id, scope, propertiesXml.toString(), null)
        }
        else {
            println 'No properties to add.'
        }
    }
}
