/*
* 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 groovy.json.JsonBuilder
import org.apache.http.impl.client.CloseableHttpClient

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

/*
 * JIRA REST API Documentation: https://docs.atlassian.com/jira/REST/latest/
 */

final def serverUrl        = props['automation/serverUrl']
final def username         = props['automation/username']
final def password         = props['automation/passwordScript'] ?: props['automation/password']
final def projectKey       = props['projectKey']
final def assignee         = props['assignee']
final def summary          = props['summary']
final def environment      = props['environment']
final def issueDescription = props['issueDescription']
final def priorityName     = props['priorityName']
final def issueTypeName    = props['issueTypeName']

// Constants
final def dueDate          = Calendar.getInstance()

// Construct an empty JIRAHelper class to call helper functions
JIRAHelper jira            = new JIRAHelper()

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

println "Server: $serverUrl"
println "Project: $projectKey"
println "Assignee: $assignee"
println "Priority: $priorityName"
println "Issue Type: $issueTypeName"
println ""

try {
    // Construct the HTTP client to allow user authentication
    CloseableHttpClient client = jira.createClient(username, password)
    try {
        // Create Issue as a HashMap object
        def fieldMap = [:]
        fieldMap.put("project", ["key": projectKey])
        fieldMap.put("issuetype", ["name": issueTypeName])
        fieldMap.put("summary", summary)
        fieldMap.put("assignee", ["name": assignee])
        fieldMap.put("duedate", dueDate)
        // Optional fields
        if (priorityName) {
            fieldMap.put("priority", ["name": priorityName])
        }
        if (environment) {
            fieldMap.put("environment", environment)
        }
        if (issueDescription) {
            fieldMap.put("description", issueDescription)
        }

        def issueMap = [:]
        issueMap.put("fields", fieldMap)

        // Change mapping to JSON and prepare it to be sent via REST call
        JsonBuilder issueJSON = new JsonBuilder(issueMap)

        if (!jira.createIssue(client, serverUrl, issueJSON)) {
            println "Create Issue failed. Review error output for details."
            System.exit(1)
        }
    }
    finally {
        client.close()
    }
}
catch (Exception e) {
    e.printStackTrace()
    throw new IllegalStateException("Full execution of create issue failed.")
}
