#!/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.urelease.plugin.util.BulkClassLoader;
import com.urbancode.air.*
import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import com.urbancode.air.XTrustProvider;
import com.urbancode.urelease.plugin.rtc.plain.api.RTCClientHelper;

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

def currentDirectory = new File(getClass().protectionDomain.codeSource.location.path).parent
//The RTC Client Plain Java API contains a very long list of jars that can not be added manually
//to the command defined in the plugin.xml.
//For that reason we need to load them dynamically before doing anything with the API
//org.apache.commons.logging_1.0.4 is conflicting with Groovy dependencies and need to be excluded
String[] exclude = ["org.apache.commons.logging_1.0.4"] as String[]
BulkClassLoader.addAllFiles(currentDirectory+"/lib/RTCClient",exclude)

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

def rtcServerUrl = props['rtcServerUrl']
def userLogin = props['userLogin']
def userPassword = props['userPassword']
def projectArea = props['projectArea']

def helper = new RTCClientHelper()
helper.login(userLogin,userPassword,rtcServerUrl)

def rtcProjectArea = helper.getProjectAreaByName(projectArea)

def types = helper.getAllWorkItemTypesSorted(rtcProjectArea)

class Item { String label; String value }
	
if (types != null) {
	if (types.size() > 0) {
	def jsonBuilder = new groovy.json.JsonBuilder()
	items = [] as List
	types.each{
			key -> 
			def item = new Item(label:key.title, value:key.title)
			items.add(item)
	}
	
	jsonBuilder(items)
	print(jsonBuilder.toString())
	}
}

helper.logout()
