/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2013. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
import groovy.json.JsonSlurper
import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpRequest;
import com.urbancode.air.AirPluginTool
import com.urbancode.air.XTrustProvider
import com.urbancode.air.plugin.DeployTools.HttpHelper
import java.util.logging.Level
import java.util.logging.Logger

final def workDir = new File('.').canonicalFile
final def airTool = new AirPluginTool(args[0], args[1])
final def props = airTool.getStepProperties()



def timeoutSeconds = props['timeout']?.trim()
def serverURL = System.getenv('AH_WEB_URL')
def componentRequestId = props['requestId']
def success = true
final def componentRequestUrl = serverURL + "/rest/deploy/componentProcessRequest/"
final def currentTime = System.currentTimeMillis()

println "Timeout : ${timeoutSeconds}"
println "Server URL: ${serverURL}"
println "Component Process Request ID: ${componentRequestId}"
println "------------------------------------------------------"


try {
    HttpHelper helper = new HttpHelper(airTool)
    DefaultHttpClient client = helper.client
    def timeout = Integer.parseInt(timeoutSeconds) * 1000
    XTrustProvider.install()
    def url = new URL(serverURL)

    def method
    def response
    def body
    def status = 0
    
    println "Get component process start time:"
    method = new HttpGet(componentRequestUrl + componentRequestId)
    response = client.execute(method)
    status = response.getStatusLine().getStatusCode()
    body = helper.getBody(response)

    if(status <200 || status > 299) {
        println("Error result code recieved : ${status}")
        println(body)
        success = false
    }
    else if(!body) {
        println("No response received from url : ${componentRequestUrl + componentRequestId}")
        success = false
    }
    else {
        def jsonObject = new JsonSlurper().parseText(body)
        def startDate = jsonObject.rootTrace?.startDate
        println "Found component start date: ${new Date(startDate)}"
        println "Current Time is: ${new Date(currentTime)}"
        if (startDate) {
            println "Process has ran for ${(currentTime-startDate)/1000} seconds"

            if (currentTime-startDate > timeout) {
                println "Timeout Expired!"
                success = false
            }
            else {
                println "Execution time is within the specified timeout."
                success = true
            }
        }
        else {
            println "Could not find the start date of the component process!"
            success = false
        }
    }
}
catch (Exception e) {
    e.printStackTrace()
    success = false
}

if (!success) System.exit(1)

System.exit 0
