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 ChangeDefectStatus extends AutomationBase {
    
    //**************************************************************************
    // CLASS
    //**************************************************************************

    //**************************************************************************
    // INSTANCE
    //**************************************************************************
    
    String defectKey
    String newState

    public void execute() {
        setupHttpClient()
        
        for (def defect : defectKey.split(",")) {
            defect = defect.trim()
            if (defect.size() > 0) {
                updateStatus(defect)
            }
        }
    }
    
    private void updateStatus(defect) {
        def workspaceRef = configureWorkspace()
        def defectType = "Defect"
        
        // Generate XML doc
        def writer = new StringWriter()
        def builder = new groovy.xml.MarkupBuilder(writer)
        builder.Defect(){
            State(newState)
        }

        def isError = false
        HttpMethod queryMethod = new GetMethod(url + defectType + "?workspace=" + URLEncoder.encode(workspaceRef, "UTF-8") + 
            "&query=" + URLEncoder.encode("(FormattedID = " + defect.trim() + ")" ,"UTF-8") + "&" + URLEncoder.encode("fetch", "UTF-8") + 
                "=" + URLEncoder.encode("true", "UTF-8"))
        def queryResult = client.executeMethod(queryMethod)
        
        String responseText = IO.readText(queryMethod.getResponseBodyAsStream())
        def queryResponse = new XmlParser().parseText(responseText).Results.Object.ObjectID[0].text()

        HttpMethod method = new PostMethod(url + defectType + "/" + queryResponse)
        method.setRequestEntity((RequestEntity)new StringRequestEntity(writer.toString(), null, null));
        def result = client.executeMethod(method)
        def response = IO.readText(method.getResponseBodyAsStream())

        //check results
        def changeResult = new XmlParser().parseText(response);
        def errors = changeResult.Errors.OperationResultError.size();
        def warnings = changeResult.Warnings.OperationResultWarning.size();

        if(errors == 0 && warnings == 0 && result >=200 && result <300) {
          println "Successfully updated item " + defect;
        }
        else {
          println "ERROR!!! Rally Server could not update item " + defect
          changeResult.Errors.OperationResultError.each { println it.text() }
          changeResult.Warnings.OperationResultWarning.each { println it.text() }
          isError = true
        }

        if(isError) {
          System.exit 1
        }
    }
}