/*
* 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 java.lang.reflect.Array
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 statusName      = props['statusName']
final def issueIdPattern  = props['issueIdPattern']
final def failMode        = FailMode.valueOf(props['failMode']);

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

println "Server: $serverUrl";
println "Status: $statusName";
println "Issue Keys: $issueIdPattern";
println "Fail mode configured for this step is ${failMode}"
println ""

def failures = 0;
def issueIdSet = [] as Set

try {
    JIRAHelper jira = new JIRAHelper()
    CloseableHttpClient client = jira.createClient(username, password)
    try {
        XMLHelper helper = new XMLHelper(issueIdPattern)
        helper.getChangesets()
        issueIdSet = helper.getIssueIdSet()

        issueIdSet.each { issueKey ->
            def status = jira.getIssueStatus(client, serverUrl, issueKey)
            if (!status) {
                failures++
                println ("Issue not found for ${issueKey}")
                if (failMode == FailMode.FAIL_FAST) {
                    throw new IllegalStateException("Issue not found for ${issueKey}")
                }
            }
            else if (status != statusName) {
                failures++
                println ("Issue ${issueKey} has status \'${status}\' which does not match \'${statusName}\'")
                if (failMode != FailMode.WARN_ONLY) {
                   System.exit(1)
                }
            }
            else {
                println ("Issue ${issueKey} has correct status: ${status}")
            }
        }
    }
    finally {
        client.close()
    }
}
catch (Exception e) {
    e.printStackTrace()
    throw new Exception("Full execution of check status failed.")
}

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 == issueIdSet.size()) {
    throw new IllegalStateException("Fail On No Updates: All checks failed!")
}
