/*
* 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 statusName      = props['statusName']
def issueIds              = props['issueIds'].split(',').collect {it.trim().replaceAll("\\s","")} as List
issueIds.removeAll("")    // Remove any empty strings
issueIds.unique()         // Remove duplicates
final def failMode        = FailMode.valueOf(props['failMode'])
def proxyHost = props['proxyHost']?.trim()
def proxyPort = props['proxyPort']?.trim()

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

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

def failures = 0

// Begin authentication steps with JIRA
JIRAHelper jira = new JIRAHelper()
DefaultHttpClient client
client = jira.createClient(username, password, proxyHost, proxyPort)

for (def issue : issueIds.sort()) {
    def status = jira.getIssueStatus(client, serverUrl, issue)
    // If status is null... fail!
    if (!status){
        failures++
        println ("Issue ${issue} status: Issue was not found.")
        if (failMode == FailMode.FAIL_FAST) {
           throw new IllegalStateException("Issue ${issue}: Issue was not found.")
        }
    // If status != given status... fail!
    } else if (status != statusName) {
        failures++
        println ("Issue ${issue} has incorrect status: ${status}")
        if (failMode == FailMode.FAIL_FAST) {
           throw new IllegalStateException("Issue ${issue} status ${status} != ${statusName}")
        }
    }
    // Otherwise, status must == given status... success!
    else {
        println ("Issue ${issue} has correct status: ${status}")
    }
    println "---------------------------------------"
}

if (failMode == FailMode.FAIL_ON_ANY_FAILURE && failures > 0) {
    throw new IllegalStateException("Fail On Any Failure: Got ${failures} failures!")
}

if (failMode == FailMode.FAIL_ON_NO_UPDATES && failures == issueIds.size()) {
    throw new IllegalStateException("Fail On No Updates: All checks failed!")
}
