/*
* 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.jacoco

import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.DefaultHttpClient

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

import com.urbancode.ubuild.ucbtool.UCBTool

public class JacocoCoverageXMLHelper {

    //**************************************************************************
    // CLASS
    //**************************************************************************

    //**************************************************************************
    // INSTANCE
    //**************************************************************************


    public JacocoCoverageXMLHelper() {
    }

    def uploadResult (reportFiles, reportName, buildLifeId) {
        XmlParser parser = new XmlParser()
        parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        parser.setFeature("http://xml.org/sax/features/namespaces", false)
        parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);

        CoverageReport report = new CoverageReport(reportName, buildLifeId)
        reportFiles.each { reportFile ->
            def rootNode = parser.parse(reportFile)
            addCounts(rootNode, "LINE", report.totals.lineCounts)
            addCounts(rootNode, "METHOD", report.totals.methodCounts)
            addCounts(rootNode, "BRANCH", report.totals.branchCounts)
            addCounts(rootNode, "COMPLEXITY", report.totals.complexityCounts)

            def nodes
            if (rootNode."group") {
                nodes = rootNode."group"
            }
            else {
                nodes = rootNode."package"
            }

            nodes.each { node ->
                CoverageGroup group
                String name = node.@name
                if (report.coverageGroups.containsKey(name)) {
                    group = report.coverageGroups.get(name)
                }
                else {
                    group = new CoverageGroup()
                    report.coverageGroups.put(name, group)
                }

                addCounts(node, "LINE", group.lineCounts)
                addCounts(node, "METHOD", group.methodCounts)
                addCounts(node, "BRANCH", group.branchCounts)
                addCounts(node, "COMPLEXITY", group.complexityCounts)
            }
        }

        def reportXml = report.generateReportXml()
        if (reportXml) {
            sendPostRequest(reportName, reportXml.toString())
        }
        else {
            println 'No report was able to be generated'
        }
    }

    private void addCounts(def node, def type, def counts) {
        def countsNode = node."counter".find{it.@"type" == type}
        if (countsNode) {
            def missedCountAttr = countsNode.@"missed"
            if (missedCountAttr) {
                counts.missed += Integer.parseInt(missedCountAttr)
            }

            def coveredCountAttr = countsNode.@"covered"
            if (coveredCountAttr) {
                counts.covered += Integer.parseInt(coveredCountAttr)
            }
        }
    }

    private void sendPostRequest(String name, String xml) {
        def descString = "Sending coverage report"
        UCBTool ucbTool = new UCBTool()
        def buildLifeId = System.getenv("BUILD_LIFE_ID")
        def baseUrl = System.getenv("WEB_URL")
        def authToken = System.getenv("AUTH_TOKEN")
        ucbTool.addTestCoverageReports(baseUrl, authToken, buildLifeId, name, xml, descString)
    }
}
