#!/usr/bin/env groovy
/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Release
 * (c) Copyright IBM Corporation 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.*

import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;

import com.urbancode.urelease.plugin.rtc.OslcHelper;

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

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

def oslcUrl = props['oslcUrl']
def oslcKey = props['oslcKey']
def oslcSecret = props['oslcSecret']
def projectArea = props['projectArea']

if (projectArea != null) {
    projectArea = projectArea.replace(" ", "%20");
}

def jsonArray = null;
def helper = new OslcHelper(oslcUrl, oslcKey, oslcSecret, projectArea)
def projects = helper.getProjectAreas ()

class Item { String label; String value }

if (projects != null) {
    if (projects.size() > 0) {
        def jsonBuilder = new groovy.json.JsonBuilder()
        items = [] as List
        projects.each{
                key ->
                //def uuid = key.itemId uuid.uuidValue
                def item = new Item(label:key.title, value:key.id)
                items.add(item)
        }
        
        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();
}