/*
* 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 QCVerifyIssues extends AutomationBase {
    
    final def PLUGIN_HOME = System.getenv()['PLUGIN_HOME']
    def outputFileName = ".violatingBugsFound.txt"
    String fieldName
    String fieldValue
    boolean useHistory = false
    boolean requireAllValues = false
        
    public void execute() {
        init()
        
        def exitcode = 0
        try {
            String defectIdString = getDefectIds()
            
            if (defectIdString) {
                def command = generateCommand(defectIdString)
                runCommand("Check Defects", command)
                verify()
            }
        }
        catch (Exception e) {
            println e
            exitcode = 1
        }
        
        if (exitcode) {
            System.exit(exitcode)
        }
    }
    
    private def generateCommand(String defectIdString) {
        def command = [cscriptExe]
        command << PLUGIN_HOME + "\\qc_verify_bug_status_history.vbs"
        command << serverUrl
        command << username
        command << password
        command << domain
        command << project
        command << defectIdString
        command << fieldName
        command << fieldValue
        command << useHistory
        command << requireAllValues
        command << outputFileName
        
        return command
    }
    
    private def getDefectIds() {
        def defectIdString
        
        def issueXml = HttpHelper.getIssuesXml()
        def issueResult = new XmlSlurper().parseText(issueXml)
    
        def issueIds = issueResult.issue.findAll{it.@"issue-tracker".text()== 'Quality Center' }.@id
        if (issueIds.size() == 0) {
            println 'No defects found. Nothing to do.'
        }
        else {
            defectIdString = issueIds.collect{it}.join(',')
            println 'Defect Ids to verify fields on: ' + defectIdString
        }
        
        return defectIdString
    }
    
    private void verify() {
        def outputFile = new File(outputFileName)
        def foundBugIds = outputFile.text.split(",").findAll{it} // drop empty
        outputFile.delete()

        if (foundBugIds) {
            println "Found ${foundBugIds.size()} defects in Quality Center which did not match."
            println "Problem defects had ids $foundBugIds"
            throw new Exception("Found ${foundBugIds.size()} defects in Quality Center which did not match.")
        }
        else {
            println "Verified defects in Quality Center."
        }
    }
}