#!/usr/bin/env groovy
/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Release
 * (c) Copyright IBM Corporation 2016. 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 java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import javax.ws.rs.core.Response;

import com.urbancode.air.plugin.jira.JiraFactory;

final def workDir = new File('.').canonicalFile

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

def jiraUrl      = props['jiraUrl']
def jiraUser     = props['jiraUser']
def jiraPassword = props['jiraPassword']
def proxyHost    = props['proxyHost']
def proxyPort    = props['proxyPort']
def proxyUser    = props['proxyUser']
def proxyPass    = props['proxyPass']

def jsonArray = null;
JiraFactory factory = new JiraFactory(jiraUrl, jiraUser, jiraPassword, proxyHost, proxyPort, proxyUser, proxyPass)
def result = factory.getAllowedCustomFields()

class Item { String label; String value }

if (result != null) {
    if (result.size() > 0) {
        items = [] as List
        result.each{
            key ->
                def item = new Item(label:key.getName(), value:key.getId())
                items.add(item)
        }

        def jsonBuilder = new groovy.json.JsonBuilder(items)
        //Old versions of UCR will look for the output printed
        print(jsonBuilder.toString())
        //New Version of UCR will look for the property "Output"
        setOutput(apTool, jsonBuilder.toString())
    }
}

//--------------------------------------------------------------    53
def setOutput(AirPluginTool apTool, String value) {
    apTool.setOutputProperty("Output", value);
    apTool.storeOutputProperties();
}
