/*
* 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 groovy.xml.StreamingMarkupBuilder;
import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.automation.JIRAHelper
import com.urbancode.air.plugin.automation.XMLHelper
import org.apache.http.impl.client.CloseableHttpClient

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']

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

println "Server: $serverUrl";
println "Issue Key Pattern: $issueIdPattern"
println ""

JIRAHelper jira = new JIRAHelper()
CloseableHttpClient client = jira.createClient(username, password)
try {
    XMLHelper helper = new XMLHelper(issueIdPattern)
    helper.getChangesets()
    def issueIdSet = helper.getIssueIdSet()
    def issueIdToChangeSetsMap = helper.getIssueIdToChangeSetListMap()
    def jiraIssues = []
    issueIdSet.each { issueKey ->
        def jiraIssue = jira.getIssue(client, serverUrl, issueKey)
        if (!jiraIssue) {
            println("\tSkipping Issue " + issueKey + ": Specified Issue not found.")
        }
        else {
            jiraIssues << jiraIssue
        }
    }
    def builder = new StreamingMarkupBuilder()
    builder.encoding = 'UTF-8'
    def issuesXml = builder.bind {
        'issues'() {
            jiraIssues.each { jiraIssue ->
                def issueKey = jiraIssue.key
                issueIdToChangeSetsMap.get(issueKey).each { changeId ->
                    'issue'("id":issueKey, "issue-tracker":"JIRA", "change-id":changeId) {
                        'name'(jiraIssue.fields?.summary)
                        'description'(jiraIssue.fields?.description)
                        'type'(jiraIssue.fields?.issuetype?.name)
                        'owner'(jiraIssue.fields?.assignee?.name)
                        'status'(jiraIssue.fields?.status?.name)
                        'url'(serverUrl + '/browse/' + issueKey)
                    }
                }
            }
        }
    }
    helper.sendPost(issuesXml.toString())
}
finally {
    client.close()
}