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 defectType
    String newState
    
    public void execute() {
        setupHttpClient()
        
        if (defectKey && defectKey.trim().length() > 0) {
            updateStatus()
        }
        else {
            println 'No issues found to update!'
        }
    }
    
    private void updateStatus() {
        def workspaceRef = configureWorkspace()
        
        // Generate XML doc
        def writer = new StringWriter()
        def builder = new groovy.xml.MarkupBuilder(writer)
        if ("Defect".equals(defectType)) {
            builder.Defect(){
                State(newState)
            }
        }
        else if ("Task".equals(defectType)) {
            builder.Task(){
                State(newState)
            }
        }

        def isError = false
        for(defect in defectKey.split(',')) {
            if (defect.trim().length() > 0) {
                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
        }
    }
}