package com.urbancode.air.plugin.automation;

import com.urbancode.air.*
import org.apache.commons.httpclient.*
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.auth.AuthScope;
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) {
              if (version > LABEL_VERSION) {
                  Number(label)
              }
              else {
                  Label(label)
              }
          }
          
          if (message) {
              Message(message)
          }
          
          Status(status)
        }
        
        HttpMethod method = new PostMethod(url)
        method.setRequestEntity((RequestEntity)new StringRequestEntity(writer.toString(), null, null));
        def result = client.executeMethod(method)
        def response = IO.readText(method.getResponseBodyAsStream())
        
        //check results
        def createResult = new XmlParser().parseText(response);
        def errors = createResult.Errors.OperationResultError.size();
        def warnings = createResult.Warnings.OperationResultWarning.size();
        
        if(errors == 0 && warnings == 0 && result >=200 && result <300) {
          println "Successfully created Build! ObjectRef =" + createResult.Object.'@ref';
          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
        }
    }
}