import groovy.xml.StreamingMarkupBuilder;

import com.urbancode.air.*;
import com.urbancode.air.plugin.automation.*;

XTrustProvider.install();

final File resourceHome = new File(System.getenv()['PLUGIN_HOME'])
final def buildLifeId = System.getenv()['BUILD_LIFE_ID']

final def apTool = new AirPluginTool(this.args[0], this.args[1])
final def props = apTool.getStepProperties()

final def serverUrl       = props['automation/serverUrl']
final def serverVersion   = props['automation/serverVersion']
final def username        = props['automation/username']
final def password        = props['automation/passwordScript'] ?: props['automation/password']
final def issueIdPattern  = props['issueIdPattern']

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

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

//Load the appropriate Jira Soap Classes into classloader
final def jiraSoapJar = new File(resourceHome, "jira-${serverVersion}.wsdl.jar")
assert jiraSoapJar.isFile();
this.class.classLoader.rootLoader.addURL(jiraSoapJar.toURL())
def JiraSoapServiceServiceLocator = Class.forName('com.atlassian.jira.rpc.soap.jirasoapservice_v2.JiraSoapServiceServiceLocator');
def RemoteIssue = Class.forName('com.atlassian.jira.rpc.soap.beans.RemoteIssue')
def RemoteComment = Class.forName('com.atlassian.jira.rpc.soap.beans.RemoteComment')
def RemoteFieldValue = Class.forName('com.atlassian.jira.rpc.soap.beans.RemoteFieldValue')
def RemotePermissionException = Class.forName('com.atlassian.jira.rpc.exception.RemotePermissionException')

// connect to Jira
String fullAddress = serverUrl + "/rpc/soap/jirasoapservice-v2";
if (!fullAddress.startsWith("http")) {
    fullAddress = "http://" + fullAddress;
}
def locator = JiraSoapServiceServiceLocator.newInstance();
locator.jirasoapserviceV2EndpointAddress = fullAddress;
def jiraSoapService = locator.getJirasoapserviceV2();
def sessionToken = jiraSoapService.login(username, password);
try {
    def statusLookup = jiraSoapService.getStatuses(sessionToken).toList().groupBy{it.id}
    def issueTypeLookup = jiraSoapService.getIssueTypes(sessionToken).toList().groupBy{it.id}
    
    XMLHelper helper = new XMLHelper(issueIdPattern)
    helper.getChangesets()
    def issueIdSet = helper.getIssueIdSet()
    def issueIdToChangeSetsMap = helper.getIssueIdToChangeSetListMap()
    def jiraIssues = []
    issueIdSet.each { issueKey ->
        def jiraIssue = jiraSoapService.getIssue(sessionToken, 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.summary)
                        description(jiraIssue.description)
                        type(issueTypeLookup[jiraIssue.type]?.name)
                        status(statusLookup[jiraIssue.status]?.name)
                    }
                }
            }
        }
    }

    helper.sendPost(issuesXml.toString())
}
finally {
    jiraSoapService.logout(sessionToken)
}