/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2017. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/

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

import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.jira.addcomments.JIRAHelper
import groovy.json.JsonBuilder
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 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']
def proxyHost = props['proxyHost']?.trim()
def proxyPort = props['proxyPort']?.trim()
def parentIssueKey = props['parentIssueKey']
def labels = props['labels']

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

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

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

println "Server:\t$serverUrl"
println "Project:\t$projectKey"
println ""

try {
    // Construct the HTTP client to allow user authentication
    DefaultHttpClient client
    client = jira.createClient(username, password, proxyHost, proxyPort)

    // Create Issue as a HashMap object
    def fieldMap = [:]
    fieldMap.put("issuetype", ["name": issueTypeName])
    fieldMap.put("project", ["key": projectKey])
    fieldMap.put("assignee", ["name": assignee])
    fieldMap.put("priority", ["name": priorityName])
    fieldMap.put("summary", summary)
    fieldMap.put("description", issueDescription)
    if (parentIssueKey?.trim()){
        fieldMap.put("parent", ["key": parentIssueKey])
    }
    else {
        fieldMap.put("environment", environment)
        fieldMap.put("duedate", dueDate)
    }
    if (labels?.trim()){
        def labelList = []
        labels.split("\n").each{ label->
            labelList.add(label)
        }
        fieldMap.put("labels", labelList)
    }

    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)
    }
}
catch (Exception e) {
    e.printStackTrace()
    throw new IllegalStateException("Full execution of create issue failed.")
}
