package com.urbancode.air.plugin.automation;

import org.apache.commons.httpclient.*
import org.apache.commons.httpclient.methods.*
import org.apache.http.client.methods.HttpGet
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 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) {
                HttpGet queryMethod = new HttpGet(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.execute(queryMethod)
                
                String responseText = IO.readText(queryResult.entity.content)
                def queryResponse = new XmlParser().parseText(responseText).Results.Object.ObjectID[0].text()

                HttpPost method = new HttpPost(url + defectType + "/" + queryResponse)
                method.setEntity(new StringEntity(writer.toString(), null, null));
                def result = client.execute(method)
                def response = IO.readText(result.entity.content)

                //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
        }
    }
}