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.ubuild.plugin.rtcworkitems.RTCWorkItemHelper;

import com.urbancode.air.*;


public class CreateDefect extends AutomationBase {
    
    //*****************************************************************************************************************
    // CLASS
    //*****************************************************************************************************************
    
    //*****************************************************************************************************************
    // INSTANCE
    //*****************************************************************************************************************
    
    String defectName
    String description
    String type
    
    String severity
    String priority
    String state
    String submitter
    String build
        
    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);
        rtcHelper.authenticateRTCUser(catalogurl, client);
        def servicesUrl = rtcHelper.getServicesUrl(catalogurl, client);
        def workItemUrl = rtcHelper.getWorkItemUrl(servicesUrl, client);
        def creationUrl = rtcHelper.getCreationUrl(servicesUrl, client);
        
        //////////////////// get Project Name code from ......... /////////////////////////////////////////////////////
        def workItemProject = workItemUrl.substring(workItemUrl.length() - 33, workItemUrl.length() - 10)
        println()
        println(catalogurl)
        println("servicesUrl: " + servicesUrl)
        println(workItemUrl)
        println(creationUrl)
        println(workItemProject)
        println()
        
//        println(getAllWorkItems(workItemUrl, client))
//        println()
        
        
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
        
        def builder = new groovy.xml.StreamingMarkupBuilder()
        builder.encoding = "UTF-8"
        def newItem = {
          mkp.xmlDeclaration()
          mkp.declareNamespace('oslc_cm':'http://open-services.net/xmlns/cm/1.0/')
          mkp.declareNamespace('rtc_cm':'http://jazz.net/xmlns/prod/jazz/rtc/cm/1.0/')
          mkp.declareNamespace('dc': 'http://purl.org/dc/terms/')
          oslc_cm.ChangeRequest{
//            rtc_cm.filedAgainst(projectName)
//            rtc_cm.filedAgainst('https://rtc.dev.urbancode.com:9443/ccm/resource/itemOid/com.ibm.team.workitem.Category/_gaAmRDfeEeKV-Zxr86NTMA') works
            rtc_cm.filedAgainst('_gaAmRDfeEeKV-Zxr86NTMA')
//            rtc_cm.filedAgainst(projectName)
            rtc_cm.type(type)
            dc.description(description)
            dc.title(defectName)
          }
          println()
//          println(oslc_cm.shortTitle)
          println()
        }
        
        String newItemStr = builder.bind(newItem)
        
        def createResult = createItem(newItemStr, creationUrl, client);
        if (createResult < 300 && createResult >= 200) {
            println("Successfully created work item.");
            System.exit(0);
        } else {
            println("Failed to create work item. Result was ${createResult}");
            System.exit(1);
        }
    }
    
    def final createItem(String newItemString, createUrl, HttpClient client) {
        HttpMethod createMethod = null;
        try {
            createMethod = new PostMethod(createUrl);
            createMethod.setRequestEntity((RequestEntity)new StringRequestEntity(newItemString));
            createMethod.setRequestHeader("Accept", "application/x-oslc-cm-change-request+xml");
            createMethod.setRequestHeader("Content-type", "application/x-oslc-cm-change-request+xml");
            def result = client.executeMethod(createMethod);
            def resp = createMethod.getResponseBodyAsString();
            if (result <300 && result >=200) {
                return result;
            }
            else {
                println newItemString
                println resp;
                return result;
            }
        }
        finally {
            if (createMethod != null) {
                createMethod.releaseConnection();
            }
        }
    }
    
    def final String getAllWorkItems(String queryUrl, HttpClient client) {
        HttpMethod queryMethod = null;
        String resp ="";
        try {
            queryMethod = new GetMethod(queryUrl + '.xml');
            queryMethod.setRequestHeader("Accept", "application/x-oslc-cm-change-request+xml");
            def result = client.executeMethod(queryMethod);
            resp = queryMethod.getResponseBodyAsString();
        }
        finally {
            if (queryMethod != null) {
                queryMethod.releaseConnection();
            }
        }
        return resp;
    }
    
}
