package com.urbancode.air.plugin.automation

import org.apache.commons.httpclient.*
import org.apache.commons.httpclient.methods.*
import org.apache.http.HttpResponse
import org.apache.http.client.HttpClient
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.httpcomponentsutil.HttpClientBuilder
import com.urbancode.commons.util.IO
import com.urbancode.ubuild.plugin.rtcworkitems.RTCWorkItemHelper


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) {
        HttpClientBuilder clientBuilder = new HttpClientBuilder()
        clientBuilder.setTrustAllCerts(true)
        HttpClient client = clientBuilder.buildClient()
        
        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 (isGoodResponseCode(createResult)) {
            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) {
        HttpPost createMethod = null;
        try {
            createMethod = new HttpPost(createUrl);
            createMethod.setEntity(new StringEntity(newItemString));
            createMethod.addHeader("Accept", "application/x-oslc-cm-change-request+xml");
            createMethod.addHeader("Content-type", "application/x-oslc-cm-change-request+xml");
            HttpResponse result = client.execute(createMethod);
            def resp = IO.readText(result.entity.content)
            def responseCode = result.statusLine.statusCode
            if (!isGoodResponseCode(responseCode)) {
                println newItemString
                println resp;
            }
            
            return responseCode
        }
        finally {
            if (createMethod != null) {
                createMethod.releaseConnection();
            }
        }
    }
    
    def final String getAllWorkItems(String queryUrl, HttpClient client) {
        HttpGet queryMethod = null;
        String resp ="";
        try {
            queryMethod = new HttpGet(queryUrl + '.xml');
            queryMethod.addHeader("Accept", "application/x-oslc-cm-change-request+xml");
            HttpResponse result = client.execute(queryMethod);
            resp = IO.readText(result.entity.content)
        }
        finally {
            if (queryMethod != null) {
                queryMethod.releaseConnection();
            }
        }
        return resp;
    }
    
    private boolean isGoodResponseCode(int responseCode) {
        return responseCode >= 200 && responseCode < 300;
    }
}
