/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* (c) Copyright IBM Corporation 2012, 2014. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
package com.urbancode.air.plugin.nunit

import org.apache.http.HttpResponse
import org.apache.http.client.HttpClient
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity

import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder
import com.urbancode.commons.util.IO

public class XMLHelper {
    
    //**************************************************************************
    // CLASS
    //**************************************************************************

    //**************************************************************************
    // INSTANCE
    //**************************************************************************
    private def testCount = 0
    private def suiteCount = 0
    private def builder
    def testSuiteStack = []
    
    public XMLHelper() {
    }
    
    def parseTestSuite (builder, testSuiteNode) {
        testSuiteStack << testSuiteNode.@name
        def testSuiteResultsNode = testSuiteNode.results
        if (testSuiteResultsNode.'test-case') {
            builder."test-suite"("name": testSuiteStack.join('.')) {
                suiteCount++
                testSuiteResultsNode.'test-case'.each { testCaseNode ->
                    if ('True'.equalsIgnoreCase(testCaseNode.@executed)) {
                        def name = testCaseNode.@name
                        def result = 'True'.equalsIgnoreCase(testCaseNode.@success) ? 'success' : 'failure'
                        def time = testCaseNode.@time
                        if (!time) {
                            time = 0
                        }
                        else {
                            time = time.replaceAll(',', '')
                            time = (long) (Double.parseDouble(time) * 1000)
                        }
                        builder."test"("name": name, "result": result, "time": time) {
                            testCount++
                            if (result == 'failure') {
                                def errorMsg = 'Message: ' + testCaseNode.failure.message.text() + ' Stack Trace: ' +  testCaseNode.failure.'stack-trace'.text()
                                "message"(errorMsg)
                            }
                        }
                    }
                }
            }
        }
        testSuiteResultsNode.'test-suite'.each { childTestSuiteNode ->
            parseTestSuite(builder, childTestSuiteNode)
            testSuiteStack.pop()
        }
    }
    
    def parseTestResults (builder, testResultsNode) {
        testResultsNode.'test-suite'.each { testSuiteNode ->
            parseTestSuite(builder, testSuiteNode)
            testSuiteStack.pop()
        }
    }

    def uploadResult (reportFiles, reportName, truncate) {
        def testSuiteStack = []
        def testsuiteName
        def result
        def name
        def time
        
        def reportXml = new java.io.StringWriter()
        builder = new groovy.xml.MarkupBuilder(reportXml)
        builder."test-report"("name": reportName, "type": 'NUnit', "build-life-id": System.getenv("BUILD_LIFE_ID")) {
            reportFiles.each { xml ->
                def rootNode = new XmlParser().parse(xml)
                if (rootNode.name().equals("test-results")) {
                    def testResultsNode = rootNode
                    parseTestResults(builder, testResultsNode)
                }
            }
        }
        
        if (reportXml) {
            sendPostRequest(reportName, reportXml.toString())
        }
        else {
            println 'No report was able to be generated'
        }
    }
    
    private void sendPostRequest(String name, String xml) {
        def authToken = System.getenv("AUTH_TOKEN")
        String buildLifeId = System.getenv("BUILD_LIFE_ID")
        name = encode(name)
        
        // construct the URL with property replacements
        String baseUrl = System.getenv("WEB_URL")
        
        baseUrl += baseUrl.endsWith("/") ? "" : "/"
        String url = baseUrl + "rest/buildlife/${buildLifeId}/tests?reportName=${name}"
        
        println "Sending request to $url"

        HttpPost postMethod = new HttpPost(url)
        if (authToken) {
            postMethod.addHeader("Authorization-Token", authToken)
            postMethod.addHeader("Content-Type", "application/xml")
        }
        
        println "Sending ${testCount} test results from ${suiteCount} test suites"
        postMethod.setEntity(new StringEntity(xml));

        HttpClientBuilder builder = new HttpClientBuilder()
        builder.setTrustAllCerts(true)
        HttpClient client = builder.buildClient()

        HttpResponse response = client.execute(postMethod)
        def responseCode = response.statusLine.statusCode
        InputStream responseStream = response.entity.content
        if (isGoodResponseCode(responseCode)) {
            IO.copy(responseStream, System.out)
            println ""
        }
        else {
            IO.copy(responseStream, System.err)
            throw new RuntimeException("Failed to upload JUnit test results. StatusCode: ${responseCode}")
        }
    }
    
    private boolean isGoodResponseCode(int responseCode) {
        return responseCode >= 200 && responseCode < 300;
    }
    
    private def encode = {
        return !it ? it : new java.net.URI(null, null, it, null).toASCIIString()
    }
}