/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* UrbanCode Build
* UrbanCode Release
* AnthillPro
* (c) Copyright IBM Corporation 2014, 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 java.util.Collections
import javax.servlet.http.*

import org.apache.http.HttpStatus
import org.apache.http.client.methods.HttpRequestBase
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.util.EntityUtils
import org.apache.http.entity.StringEntity

import org.apache.http.NameValuePair
import org.apache.http.message.BasicNameValuePair
import org.apache.http.client.entity.UrlEncodedFormEntity


import groovy.json.JsonSlurper
import groovy.json.JsonOutput



import com.urbancode.air.XTrustProvider
import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder
import com.urbancode.commons.util.FilePatternFileFilter
import com.urbancode.commons.util.IO
import com.urbancode.air.AirPluginTool

final AirPluginTool airPluginTool = new AirPluginTool(this.args[0], this.args[1])
final Properties props = airPluginTool.getStepProperties()


def instanaUrl = props['instanaUrl'].trim()
def apiKey = props['apiKey'].trim()
def pipelineName = props['pipelineName'].trim()
boolean disableCerts = Boolean.valueOf(props['disableCerts'])

def timestamp = System.currentTimeMillis()
String timestamp1 = timestamp.toString()
def exitVal = 0


println ("pipelineName: ${pipelineName}")

println ("instanaUrl: ${instanaUrl}")

println ("apiKey: ${apiKey}")

def response = executeHttpRequest(instanaUrl,  apiKey, pipelineName, timestamp1, disableCerts)
if (!response) {
    throw new Exception("[Error] Could not complete task.")
}


private def executeHttpRequest(String uri, apiKey, pipelineName, timestamp, disableCerts) {
    CloseableHttpClient client
    HttpClientBuilder builder = new HttpClientBuilder()

    if(disableCerts) {
        XTrustProvider.install()
        builder.setTrustAllCerts(true)
    }

    client = builder.buildClient()

    HttpPost getPostMethod = new HttpPost(uri + '/api/releases')
    getPostMethod.addHeader("Content-Type", "application/json");
    getPostMethod.addHeader("Authorization", "apiToken ${apiKey}");
    

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

    String inputJson = "{\n    \"name\": \"${pipelineName}\",\n    \"start\": \"${timestamp}\"\n}"
 
    StringEntity stringEntity = new StringEntity(inputJson);

    getPostMethod.setEntity(stringEntity)
    


    CloseableHttpResponse response
    try {
        response = client.execute(getPostMethod)
        println ("Response: ${response}")
        println (response.getStatusLine().toString())
        
        def statusCode = response.getStatusLine().getStatusCode()
        println(statusCode)
        if(statusCode != 200) {
            exitVal = 1
            println(exitVal)
            System.exit(exitVal)
        }

        def entity = EntityUtils.toString(response.getEntity())
        def slurper = new JsonSlurper();
        def parsedJson = slurper.parseText(entity)
        println ("Response Body: ${parsedJson}")
        
    }
    catch (IOException e) {
        println ("[Error] Problem executing HTTP request: ${e.getMessage()}.")
        println ("Response: ${response}")
        return false
    }
    return response
}

private URI encodeUri(String uri) {
    if (!uri.startsWith('http://') && !uri.startsWith('https://')) {
        uri = 'https://' + uri
    }
    URL rawUri = new URL(uri)
    return new URI(rawUri.getProtocol(),
                    rawUri.getAuthority(),
                    rawUri.getPath(),
                    rawUri.getQuery(),
                    rawUri.getRef())
}

System.exit(exitVal)
