/**
* 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 statusName      = props['statusName']
def issueIds              = TextUtil.textToList(props['issueIds'], true)
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 "Status:\t$statusName"
println "Issue Keys:\t$issueIds"
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, allowInsecure)

for (def issue : issueIds) {
    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!")
}
