/**
* Licensed Materials - Property of IBM* and/or HCL**
* IBM UrbanCode Deploy
* (c) Copyright IBM Corporation 2010, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/

/*
 * 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 com.urbancode.air.plugin.jira.addcomments.TextUtil
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 username        = props['username']
final def password        = props['passwordScript']?:props['password']
final def issueIds        = TextUtil.textToList(props['issueIds'], true)
final def commentBody     = props['commentBody']
final def failMode        = FailMode.valueOf(props['failMode'])
def proxyHost = props['proxyHost']?.trim()
def proxyPort = props['proxyPort']?.trim()
boolean allowInsecure = (props['allowInsecure']?:"false").toBoolean()

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

println "Server:\t$serverUrl"
println "Issue Ids:\t$issueIds"
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, allowInsecure)

        // 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])
    }
}
