/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* (c) Copyright IBM Corporation 2012, 2014. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
package com.urbancode.air.plugin.automation;

import org.apache.commons.httpclient.*
import org.apache.commons.httpclient.methods.*
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.ContentType
import org.apache.http.entity.StringEntity
import org.codehaus.jettison.json.JSONObject

import com.urbancode.air.*
import com.urbancode.commons.util.IO

public class ReportBuildStatus extends AutomationBase {
    
    String buildDefId
    String duration
    String label
    String message
    String status
    
    public void execute() {
        setupHttpClient()
        
        def jsonBuild = new JSONObject()
        jsonBuild.put('BuildDefinition', buildDefId)
        if (duration) {
            jsonBuild.put('Duration', duration)
        }
        if (message) {
            jsonBuild.put('Message', message)
        }
        if (label) {
            jsonBuild.put('Number', label)
        }
        jsonBuild.put('Status', status)
        
        def json = new JSONObject()
        json.put('Build', jsonBuild)

		def key = getKey()
		def createBuildUrl = url + 'build/create?key=' + URLEncoder.encode(key, 'UTF-8')

        HttpPost method = new HttpPost(createBuildUrl)
        try {
	        method.setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));
	        def response = client.execute(method)
	        def responseCode = response.statusLine.statusCode
	        def content = IO.readText(response.entity.content)
	        
            def createResult = new JSONObject(content).get('CreateResult')
            def errors = createResult.get('Errors')
            def warnings = createResult.get('Warnings')

            if (errors.length() == 0 && isGoodResponseCode(responseCode)) {
          		if (warnings.length() > 0) {
              		println "Warnings: $warnings"
          		}
              	println "Successfully created build"
            }
            else {
              	println "ERROR!!! Failed to create build"
              	if (errors.length() > 0) {
              		println "Errors: $errors"
          		}
          		if (warnings.length() > 0) {
              		println "Warnings: $warnings"
          		}
                throw new RuntimeException("Rally server did not create build. StatusCode: ${responseCode}")
            }
        }
        finally {
        	method.releaseConnection()
        }
    }
}