/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2016. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/

import org.apache.http.message.BasicNameValuePair

import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.automation.RallyHelper

// Get step variables
AirPluginTool apTool = new AirPluginTool(this.args[0], this.args[1])
Properties inProps = apTool.getStepProperties()

String rallyUrl    = inProps['rallyUrl']
String rallyVer    = inProps['rallyVer']
String workspace   = inProps['workspace']
String rallyUser   = inProps['rallyUser']
String rallyPass   = inProps['rallyPass']
String rallyApiKey = inProps['rallyApiKey']
String proxyHost   = inProps['proxyHost']
String proxyPort   = inProps['proxyPort']
String proxyPass   = inProps['proxyPass']
String proxyUser   = inProps['proxyUser']

String defectKey = inProps['defectKey']
String taskKey   = inProps['taskKey']
String usKey     = inProps['usKey']
String comment   = inProps['comment']

// Set up RallyHelper
RallyHelper.setupHttpClient(rallyApiKey, rallyUser, rallyPass, proxyHost, proxyPort, proxyUser, proxyPass)
String workspaceRef = RallyHelper.configureWorkspace(rallyUrl, rallyVer, workspace)

// Get lists
ArrayList<String> defects = RallyHelper.makeList(defectKey)
ArrayList<String> tasks = RallyHelper.makeList(taskKey)
ArrayList<String> stories = RallyHelper.makeList(usKey)

// Add comments to all artifacts
int totalCommentsAdded = 0
totalCommentsAdded += addComments(workspaceRef, rallyVer, 'defect', defects, comment)
totalCommentsAdded += addComments(workspaceRef, rallyVer, 'task', tasks, comment)
totalCommentsAdded += addComments(workspaceRef, rallyVer, 'hierarchicalrequirement', stories, comment)
println ("\n\n----- Summary: ${totalCommentsAdded}/${defects.size() + tasks.size() + stories.size()} comments successfully added -----")
if (totalCommentsAdded == (defects.size() + tasks.size() + stories.size())) {
    println ('[ok]  All comments added successfully.')
    System.exit(0)
}
else {
    println ('[error]  Not all comments added.')
    System.exit(1)
}

/**
*  @param workspaceRef The url reference of the workspace the artifacts are in
*  @param rallyVer The version of the Rally Server
*  @param artifactTyp The type of the artifact
*  @param artifacts The List of artifacts to add the comment to
*  @param comment The comment to append to the artifacts
*  @return The number of artifacts that had comments successfully added
*/
private int addComments(String workspaceRef, String rallyVer, String artifactType, ArrayList<String> artifacts, String comment) {
    int successfulAdditions = 0
    artifacts.eachWithIndex { artifact, index ->
        println ("\n----- Working on ${artifactType} ${index + 1}/${artifacts.size()} -----")

        // Get artifact id
        println ("\n[action]  Retrieving ObjectID for ${artifactType} ${artifact}")
        List<BasicNameValuePair> queryParams = new LinkedList<BasicNameValuePair>()
        queryParams.add(new BasicNameValuePair('workspace', workspaceRef))
        queryParams.add(new BasicNameValuePair('query', "(FormattedID = ${artifact})"))
        queryParams.add(new BasicNameValuePair('fetch', 'true'))
        String body = RallyHelper.executeHttpGet(artifactType, queryParams)

        def artifactId = RallyHelper.getElement(body, 'Results.Object.ObjectID', 'QueryResult.Results.ObjectID')
        if (artifactId) {
            artifactId = artifactId
            println ("[ok]  ObjectID found: ${artifactId}.")
        }
        else {
            println ('[error]  Could not determine artifact ID.')
            System.exit(1)
        }

        // Generate POST content
        HashMap<String, String> children = new HashMap<String, String>()
        children.put('Artifact', artifactId)
        children.put('Text', comment)
        children.put('Workspace', workspaceRef)
        String updateInfo = RallyHelper.buildPost('ConversationPost', children)

        // Add comment to artifact
        println ("\n[action]  Adding comment for ${artifactType} ${artifact}...")
        String postResponse = RallyHelper.executeHttpPost('conversationpost/create', updateInfo)

        // Process returned response
        println ('\n[action]  Checking response from Rally Server...')
        RallyHelper.printWarngingsAndErrors(postResponse, 'Create')
        def commentId
        def commentRef = RallyHelper.getElement(postResponse, 'Object.@ref', 'CreateResult.Object._ref')
        if (!commentRef) {
            println ('[error]  Could not add comment.')
            return false
        }
        commentId = commentRef.substring(commentRef.lastIndexOf('/') + 1)
        if (commentId) {
            println ('[ok]  Successfully added comment.')
            successfulAdditions++
        }
        else {
            println ('[error]  Comment not added.')
            return false
        }
    }
    return successfulAdditions
}
