#!/usr/bin/env groovy
/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Release
 * (c) Copyright IBM Corporation 2014, 2017. 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.JiraApplication;
import com.urbancode.air.plugin.jira.JiraComponent;
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.getAllApplications(false, false)

class Item { String label; String value }

if (result != null) {
    if (result.size() > 0) {
        List<Item> items = new ArrayList<Item>()
        for (JiraApplication app : result) {
            Item item = new Item(label:app.getName(), value:app.getId())
            items.add(item)
            for (JiraComponent comp : app.getComponents()) {
                item = new Item(label:app.getName() + ": " + comp.getName(), value:comp.getId())
                items.add(item)
            }
        }


        def jsonBuilder = new groovy.json.JsonBuilder(items.sort{ it.label })
        //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();
}
