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

/*
 * JIRA REST API Documentation: https://docs.atlassian.com/jira/REST/latest/
 */

import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.jira.addcomments.FailMode
import com.urbancode.air.plugin.jira.addcomments.JIRAHelper
import org.apache.http.impl.client.DefaultHttpClient

final def apTool = new AirPluginTool(this.args[0], this.args[1])
final def props = apTool.getStepProperties()

final def serverUrl       = props['serverUrl']
final def serverVersion   = props['serverVersion']
final def username        = props['username']
final def password        = props['passwordScript']?:props['password']
final def issueIds        = props['issueIds'].split(',').collect{it.trim().replaceAll("\\s","")} as List
issueIds.removeAll("")    // Remove any empty strings
issueIds.unique()         // Remove duplicates
final def commentBody     = props['commentBody']
final def failMode        = FailMode.valueOf(props['failMode'])
def proxyHost = props['proxyHost']?.trim()
def proxyPort = props['proxyPort']?.trim()

//------------------------------------------------------------------------------
// Script content
//------------------------------------------------------------------------------

println "Server:\t$serverUrl"
print "Issue Ids:\t"
println issueIds.sort()
println "Comment:\t$commentBody"
println "Fail mode configured for this step is ${failMode}"
println ""

def issueNotFoundExceptions = []   // for non FAIL_FAST modes format
JIRAHelper jira = new JIRAHelper() // Created to call helper methods from JIRAHelper
DefaultHttpClient client           // Each add comment reinitializes this variable

// Construct the comment that will be sent via the REST command
String body = '{"body":"' + commentBody + '"}'

//------------------------------------------------------------------------------
// Iterate through each of the issues, POST the comment, and analyze the return status code
//------------------------------------------------------------------------------
try {
    for (def issueId : issueIds) {
        // Construct the client to allow the authentication of the user
        client = jira.createClient(username, password, proxyHost, proxyPort)

        // Add comment to Issue... return true or false based on success
        if (!jira.addIssueComment(client, serverUrl, issueId, body)) {
            issueNotFoundExceptions << "${issueId} failed to add comment"
            if (failMode == FailMode.FAIL_FAST) {
                throw new IllegalStateException("Fail Fast: Add comment failed. " +
                    "Review error output for details.")
            }
        }
        println "---------------------------------------"
    }
}
catch (Exception e) {
    e.printStackTrace()
    throw new Exception("Full execution of add comment failed.")
}

//------------------------------------------------------------------------------
// Check post conditions
//------------------------------------------------------------------------------

// Check if no issues were specified
if (failMode == FailMode.FAIL_ON_NO_UPDATES && !issueIds) {
    throw new IllegalStateException("No issues specified.")
}

// Check which issues failed to add a comment
if (issueNotFoundExceptions.size() > 0) {
    println("Failed to add comments to " + issueNotFoundExceptions.size() + " issues")
    if (failMode == FailMode.FAIL_ON_NO_UPDATES &&
            issueIds.size() == issueNotFoundExceptions.size()) {
        // throw the first exception we found as our failure
        throw new IllegalStateException("Initial Error: " + issueNotFoundExceptions[0])
    }
}
