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

import com.urbancode.air.http.*

public class QCPublishTestReport extends AutomationBase {

    String folder
    String testSetName
    String remoteHost
    String reportName
    String jobId
    
    private File outputFile = new File("qc-test-report-" + new Random().nextInt() + ".xml")
    
    public void execute() {
        init()
        
        def command = generateCommand()
        runCommand("Publishing Test Results", command)
        
        try {
            String url = generateUrl()
            HttpHelper.sendPostRequest(url, outputFile)
        }
        finally {
            outputFile.delete()
        }
    }
    
    private def generateCommand() {
        def command = [cscriptExe]
        command << PLUGIN_HOME + "\\qc_publish_test_report.vbs"
        command << serverUrl
        command << username
        command << password
        command << domain
        command << project
        command << folder
        command << reportName
        command << testSetName
        command << jobId
        command << outputFile
        
        return command
    }
    
    private def generateUrl() {
        String buildLifeId = System.getenv("BUILD_LIFE_ID")
        
        // construct the URL with property replacements
        String baseUrl = System.getenv("WEB_URL")
        baseUrl += baseUrl.endsWith("/") ? "" : "/"
        
        def encodedReportName = URLEncoder.encode(reportName)
        String url = baseUrl + "rest/buildlife/${buildLifeId}/tests?reportName=${encodedReportName}"
        
        return url
    }
}