package com.urbancode.air.plugin.automation

import com.urbancode.air.http.*
import groovy.xml.XmlUtil
import org.jsoup.Jsoup;

public class QCPublishBugReport extends AutomationBase {
    
    def issueIds
    def failMode
    def outputFileName
    
    private def outputFile
    
    public void execute() {
        init()   

        if (!issueIds) {
            println 'No bugs have been chosen!'
        }
        else {
            uploadBugReport()
        }
    }
    
    
    private uploadBugReport() {
        def command = generateCommand()
        runCommand("Retrieving Bug Details", command)
        
        outputFile = new File(outputFileName)
        
        // read file and rewrite the description without HTML
        def issuesXml = new XmlParser().parse(outputFile)
        def descriptions = issuesXml.depthFirst().findAll { it.name() == 'description' }
        println "Found ${descriptions.size()} descriptions"
        descriptions.each { description ->
            description.value = Jsoup.parse(description.text()).text()
        }
        
        outputFile.write(XmlUtil.serialize(issuesXml))
        println "Output file written to " + outputFile.absoluteFile
    }
    
    private def generateCommand() {
        def getBugDetailsCommand = [cscriptExe]
        getBugDetailsCommand << PLUGIN_HOME + "\\qc_get_bug_details.vbs"
        getBugDetailsCommand << serverUrl
        getBugDetailsCommand << username
        getBugDetailsCommand << password
        getBugDetailsCommand << domain
        getBugDetailsCommand << project
        getBugDetailsCommand << issueIds
        getBugDetailsCommand << outputFileName
        
        return getBugDetailsCommand
    }   
}