package com.urbancode.air.plugin.automation

import org.apache.commons.httpclient.*
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.auth.AuthScope;

import com.urbancode.air.*

import com.urbancode.ubuild.plugin.rtcworkitems.RTCWorkItemHelper;


public class ChangeDefectStatus extends AutomationBase {
    
    //*****************************************************************************************************************
    // CLASS
    //*****************************************************************************************************************
    
    //*****************************************************************************************************************
    // INSTANCE
    //*****************************************************************************************************************
    
    def ids
    String workflowType
    String newState
    
    def etag
    
    public void execute(props, apTool) {
        HttpClient client= new HttpClient();
        
        XTrustProvider.install();
        def rtcHelper = new RTCWorkItemHelper(props, apTool);
        def catalogurl = rtcHelper.getCatalogUrl(client);
        rtcHelper.authenticateRTCUser(catalogurl, client);
        def servicesUrl = rtcHelper.getServicesUrl(catalogurl, client);
        def workItemUrl = rtcHelper.getWorkItemUrl(servicesUrl, client);
        
        ids.each { workItem ->
            def workItemRep = getWorkItemByIdentifier(workItem, workItemUrl, client);
//            println workItemRep;
            if (!workItemRep) {
                println "Unable to find work item $workItem";
                return;
            }
            String currWorkItemUrl = url + '/resource/itemName/com.ibm.team.workitem.WorkItem/' + workItem;
            def updateResult = updateItem(currWorkItemUrl, client);
            if (updateResult < 300 && updateResult >= 200) {
                println("Successfully updated work item $workItem");
            } else {
                println("Failed to update work item $workItem, result was $updateResult");
            }
            
        }
    }
    
    def final String getWorkItemByIdentifier(String identifier, String queryUrl, HttpClient client) {
        HttpMethod queryMethod = null;
        String resp ="";
        try {
            queryMethod = new GetMethod(queryUrl + '.xml?oslc_cm.query=' + URLEncoder.encode('dc:identifier="' + identifier + '"', "UTF-8"));
            queryMethod.setRequestHeader("Accept", "application/x-oslc-cm-change-request+xml");
            def result = client.executeMethod(queryMethod);
            etag = queryMethod.getResponseHeader("ETag").getElements()[0].getName()
            resp = queryMethod.getResponseBodyAsString();
        }
        finally {
            if (queryMethod != null) {
                queryMethod.releaseConnection();
            }
        }
        return resp;
    }
    
    def final updateItem(createUrl, HttpClient client) {
        PutMethod changeStatusMethod = null;
        try {
            changeStatusMethod = new PutMethod(createUrl);
            String command = 'com.ibm.team.workitem.defectWorkflow.action.';
            switch (newState) {
                case "Resolve"          : command += 'resolve';
                                          break;
                case "Start Working"    : command += 'startWorking';
                                          break;
                case "Stop Working"     : command += 'stopWorking';
                                          break;
                case "Verify"           : command += 'verify';
                                          break;
                case "Confirm"          : command += 'confirm';
                                          break;
                case "Reopen"           : command += 'reopen';
                                          break;
                default                 : command = workflowType + '.action.' + newState;
                                          break;
            }
            changeStatusMethod.setQueryString("_action=${command}")
            println("Query URL = " + createUrl + changeStatusMethod.getQueryString());
            changeStatusMethod.setRequestHeader("Accept", "application/x-oslc-cm-change-request+xml");
            changeStatusMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            changeStatusMethod.setRequestHeader("ETag", etag)
            def result = client.executeMethod(changeStatusMethod);
            def resp = changeStatusMethod.getResponseBodyAsString();
            if (result <300 && result >=200) {
                return result;
            }
            else {
                println resp;
                return result;
            }
        }
        finally {
            if (changeStatusMethod != null) {
                changeStatusMethod.releaseConnection();
            }
        }
    }
    
}
