package com.urbancode.air.plugin.automation

import java.io.File;

public class QCRunTest extends AutomationBase {
    
    String folder
    String testSetName
    String remoteHost
    int threshold
    private File outputFile = new File("qc-test-results-" + new Random().nextInt() + ".xml")
    
    public int execute() {
        init()
        
        def command = generateCommand()
        runCommand("Running Test Set", command)
        
        return verifyThresholdPassed()
    }
    
    private def generateCommand() {
        def command = [cscriptExe]
        command << PLUGIN_HOME + "\\qc_run_test_set.vbs"
        command << serverUrl
        command << username
        command << password
        command << domain
        command << project
        command << folder
        command << testSetName
        command << outputFile
        if (remoteHost) {
            command << remoteHost
        }
        
        return command
    }
    
    private int verifyThresholdPassed() {
        def found
        int totalTests = 0
        int testsPassed = 0
        outputFile.eachLine {
            found = it.find(~'^Total Tests: (.*)$') { match, tests -> return tests }
            if (found) {
                totalTests = Integer.valueOf(found)
            }
            
            found = it.find(~'^Tests Passed: (.*)$') { match, passed -> return passed }
            if (found) {
                testsPassed = Integer.valueOf(found)
            }
        }
        
        int percentPass = ((double) testsPassed / (double) totalTests) * 100
        
        if (percentPass < threshold) {
            println("Not enough tests were successful. The threshold was ${threshold} and the " +
                "passing percentage was ${percentPass}")
            return 1
        }
        return 0
    }
}