' 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.
'======================== Functions ========================
Dim tdConnection

Function disconnect()
    If IsObject(tdConnection) Then
        If tdConnection.Connected Then
            tdConnection.Disconnect()
            WScript.StdOut.WriteLine "Connection disconnected"
        End If
        If tdConnection.LoggedIn Then
            tdConnection.Logout()
            WScript.StdOut.WriteLine "Connection logged out"
        End If
        tdConnection.ReleaseConnection()
        WScript.StdOut.WriteLine "Connection released"
    End If
End Function

Function createConnection(serverUrl, username, password, domain, project)
    Dim connectionCreated
    connectionCreated = False
    
    Set tdConnection = CreateObject("TDApiOle80.TDConnection")

    If tdConnection Is Nothing Then
      WScript.StdOut.WriteLine = "Failed to create TDApiOle80.TDConnection Object"
    Else
      tdConnection.InitConnectionEx(serverUrl)
      If tdConnection.Connected = False Then
        WScript.StdOut.WriteLine "Connection failed to Quality Center server " & serverUrl
      Else
        WScript.StdOut.WriteLine "Connection created to Quality Center server " & serverUrl
        tdConnection.Login username, password
        If tdConnection.LoggedIn = False Then
          WScript.StdOut.WriteLine "Connection failed to log in as user " & username
        Else
          WScript.StdOut.WriteLine "Connection logged in as user " & username
          tdConnection.Connect domain, project
          If tdConnection.ProjectConnected = False Then
            WScript.StdOut.WriteLine "Connection failed to open project " & domain & "\" & project
          Else
            WScript.StdOut.WriteLine "Connection opened project " & domain & "\" & project
            connectionCreated = True
          End If
        End If
      End If
    End If
    
    If Not connectionCreated Then
        disconnect()
    End If
    
    createConnection = connectionCreated
End Function

'======================== Main Script ========================
Dim args
Set args = WScript.Arguments
serverUrl = args.Item(0)
username = args.Item(1)
password = args.Item(2)
domain = args.Item(3)
project = args.Item(4)
bugIds = args.Item(5)
targetFieldName = args.Item(6)
requiredValues = Split(args.Item(7),",")
useHistory = args.Item(8)
requireAll = args.Item(9)
outputFile = args.Item(10) ' contains list of problem bug ids

connectionCreated = createConnection(serverUrl, username, password, domain, project)
If Not connectionCreated Then
    WScript.Quit 1
End If

Dim badBugIds
badBugIds = ""

Dim bugFactory
Set bugFactory = tdConnection.BugFactory

Dim bug
bugIdArray = Split(bugIds, ",")
For Each bugId In bugIdArray

    Dim missingValues ' the set of values we expect to find for this bug
    Set missingValues=CreateObject("Scripting.Dictionary")
    Dim value
    For Each value In requiredValues
        missingValues.Add value,"0"
    Next

    Set bug = bugFactory.Item(bugId)
    If IsNull(bug) Then
        WScript.StdOut.WriteLine "Warning: no defect found for id " & bugId
    ElseIf useHistory <> "true" Then
        Dim fieldValue
        WScript.StdOut.WriteLine "Found defect for id " & bugId
        fieldValue = bug.Field(targetFieldName)
        If Not(missingValues.exists(fieldValue)) Then
            WScript.StdOut.WriteLine "Warning: Defect with id " & bugId & " had value " & fieldValue & " for field " _
                & targetFieldName & " instead of expected " & requiredValues
            If Len(badBugIds) > 0 Then
              badBugIds = badBugIds & ","
            End If
            badBugIds = badBugIds & bugId
        End If
    Else
        WScript.StdOut.WriteLine "Found defect for id " & bugId
        Dim history
        Dim historyList
        Set history = bug.History
        Set historyList = history.NewList("[FieldName]" & targetFieldName) ' should only return hist records for the target field
        Dim histRec
        ' WScript.StdOut.WriteLine " Bug " & bugId & " - Found " & historyList.Count & " history items for field " & targetFieldName
        For Each histRec In historyList
            ' WScript.StdOut.WriteLine "    Found New Value " & histRec.NewValue
            If missingValues.Exists(histRec.NewValue) Then missingValues.Remove(histRec.NewValue)
        Next
        
        ' UBound give the last position in the array, i.e. the size
        If requireAll = "false" AND missingValues.Count = UBound(requiredValues) Then
            WScript.StdOut.WriteLine "Warning: Defect with id " & bugId & " was missing required values " & requiredValues
            ' append the bad bug id to our output string
            If Len(badBugIds) > 0 Then
              badBugIds = badBugIds & ","
            End If
            badBugIds = badBugIds & bugId
            
        ElseIf requireAll = "true" AND missingValues.Count <> 0 Then
            For Each missingValue In missingValues.Keys
                WScript.StdOut.WriteLine "Warning: Defect with id " & bugId & " was missing required historical value " & missingValue
            Next
            ' append the bad bug id to our output string
            If Len(badBugIds) > 0 Then
              badBugIds = badBugIds & ","
            End If
            badBugIds = badBugIds & bugId
        End If
        
    End If
Next

disconnect()

' write our result of bad bug ids to the output file
Set fileSystemObject = CreateObject("Scripting.FileSystemObject")
Set textFile = fileSystemObject.OpenTextFile(outputFile, 2, True)
textFile.Write badBugIds
textFile.Close

WScript.Quit(-666)