#!/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 com.urbancode.release.rest.framework.Clients
import com.urbancode.release.rest.models.Application

import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import javax.ws.rs.core.Response;

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

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

String releaseToken = props['releaseToken']
String serverUrl = props['releaseServerUrl']

Clients.loginWithToken(serverUrl, releaseToken)

Application appEntity = new Application()
appEntity.format("name")
Application[] ucrApplications = appEntity.getAll()

class Item { String label; String value }

if (ucrApplications != null) {
    if (ucrApplications.length > 0) {
        List<Item> items = new ArrayList<Item>()
        for (Application app : ucrApplications) {
            Item item = new Item(label:app.getName(), value:app.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();
}
