/*
* 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.
*/

import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.automation.JIRAHelper
import com.urbancode.air.plugin.automation.FailMode
import com.urbancode.air.plugin.automation.XMLHelper
import org.apache.http.impl.client.CloseableHttpClient

/*
 * JIRA REST API Documentation: https://docs.atlassian.com/jira/REST/latest/
 */
final def apTool = new AirPluginTool(this.args[0], this.args[1])
final def props = apTool.getStepProperties()

final def serverUrl       = props['automation/serverUrl']
final def username        = props['automation/username']
final def password        = props['automation/passwordScript'] ?: props['automation/password']

final def issueIdPattern  = props['issueIdPattern']

final def commentBody     = props['commentBody']
final def failMode        = FailMode.valueOf(props['failMode'])

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

println "Server: $serverUrl";
println "Issue Ids: $issueIdPattern"
println "Comment: $commentBody"
println "Fail mode configured for this step is ${failMode}"
println ""

def issueNotFoundExceptions = []; // for non FAIL_FAST modes
def issueIdSet = [] as Set
JIRAHelper jira = new JIRAHelper()
CloseableHttpClient client
// 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 {
    XMLHelper helper = new XMLHelper(issueIdPattern)
    helper.getChangesets()
    issueIdSet = helper.getIssueIdSet()

    issueIdSet.each { issueId ->
        // Construct the client to allow the authentication of the user
        client = jira.createClient(username, password)
        try {
            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.")
                }
            }
        }
        finally {
            client.close()
        }
    }
}
catch (Exception e) {
    e.printStackTrace()
    throw new Exception("Full execution of add comment failed.")
}

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