/*
* 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.quality.pmd

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
    
    public XMLHelper() {
    }
    
    def uploadResult (reportName, buildLifeId, outputFile, workDirPath) {
        def reportXml = new java.io.StringWriter()
        new groovy.xml.MarkupBuilder(reportXml).
        "analytics"("name":reportName, "buildLifeId":buildLifeId, "type":"PMD") {
            def addFinding = { findingId, findingFile, findingLine, findingName, findingSeverity, findingDesc, findingStatus ->
                if (findingFile.startsWith(workDirPath)) {
                    findingFile = findingFile.substring(workDirPath.length() + 1)
                }
                "finding"() {
                    "id"(findingId)
                    "file"(findingFile)
                    "line"(findingLine)
                    "name"(findingName)
                    "severity"(findingSeverity)
                    "description"(findingDesc)
                    "status"(findingStatus)
                }
            }
            
            def handler = new PMDHandler(addFinding)
            def reader = javax.xml.parsers.SAXParserFactory.newInstance().newSAXParser().XMLReader
            reader.setContentHandler(handler)
            def inputStream = new FileInputStream(outputFile)
            reader.parse(new org.xml.sax.InputSource(inputStream))
        }
        
        if (reportXml) {
            println 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 = URLEncoder.encode(name)
        
        // construct the URL with property replacements
        String baseUrl = System.getenv("WEB_URL")
        
        baseUrl += baseUrl.endsWith("/") ? "" : "/"
        String url = baseUrl + "rest/buildlife/${buildLifeId}/sourceanalytics?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")
        }
        
        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 PMD report. StatusCode: ${responseCode}")
        }
    }
    
    private boolean isGoodResponseCode(int responseCode) {
        return responseCode >= 200 && responseCode < 300;
    }
}