#!/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']

class Item { String label; String value }

def helper = new RTCClientHelper()

try {
    helper.login(userLogin,userPassword,rtcServerUrl)
    
    def rtcProjectArea = helper.getProjectAreaByName(projectArea)
    
    def queries = helper.getAllQueriesSorted(rtcProjectArea)
    queries.sort()
        
    if (queries != null) {
        if (queries.size() > 0) {
            def jsonBuilder = new groovy.json.JsonBuilder()
            items = [] as List
            queries.each{
                    key -> 
                    def item = new Item(label:key.title, value:key.title)
                    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())
        }
    }

}
catch (Exception ex) {
    System.prinln("Error while retrieving RTC Client Queries: "+ex);
}
finally {
    //Whatever happen we need to shutdown the process
    helper.logout()
}

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