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.StringEntity

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

public class ReportBuildStatus extends AutomationBase {
    
    //**************************************************************************
    // CLASS
    //**************************************************************************
    // The last version that used labels on build objects was 1.20
    private static String LABEL_VERSION = "1.20"

    //**************************************************************************
    // INSTANCE
    //**************************************************************************
    
    String buildDefId
    String duration
    String label
    String message
    String status
    
    public void execute() {
        reportStatus()
    }
    
    private void reportStatus() {
        setupHttpClient()
        
        // Generate XML doc
        def writer = new StringWriter()
        def builder = new groovy.xml.MarkupBuilder(writer)
        builder.Build(){
          BuildDefinition(buildDefId)
          
          if (duration) {
              Duration(duration)
          }
          
          if (label) {
              // Version 1.20+ expects Number, but these two accomplish the same thing
              Number(label)
              Label(label)
          }
          
          if (message) {
              Message(message)
          }
          
          Status(status)
        }
        
        HttpPost method = new HttpPost(url)
        method.setEntity(new StringEntity(writer.toString(), null, null));
        def result = client.execute(method)
        def responseCode = result.statusLine.statusCode
        def response = IO.readText(result.entity.content)
        
        //check results
        def createResult = new XmlParser().parseText(response);
        def errors = createResult.Errors.OperationResultError.size();
        def warnings = createResult.Warnings.OperationResultWarning.size();
        
        if(errors == 0 && responseCode >=200 && responseCode <300) {
          println "Successfully created Build! ObjectRef =" + createResult.Object.'@ref';
          
          if (warnings > 0) {
              createResult.Warnings.OperationResultWarning.each { println it.text() }
          }
          
          System.exit 0
        }
        else {
          println "ERROR: Rally Server could not create Build "
          createResult.Errors.OperationResultError.each { println it.text() }
          createResult.Warnings.OperationResultWarning.each { println it.text() }
          System.exit 1
        }
    }
}