#!/usr/bin/env groovy
/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Release
 * (c) Copyright IBM Corporation 2015, 2016. 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.air.plugin.tfs.MapBuilder
import com.urbancode.air.plugin.tfs.TFSFactory

import com.microsoft.tfs.core.clients.workitem.project.Project
import com.microsoft.tfs.core.clients.workitem.query.WorkItemCollection
import com.microsoft.tfs.core.clients.workitem.wittype.*
import com.microsoft.tfs.core.clients.workitem.WorkItem
import com.microsoft.tfs.core.clients.workitem.WorkItemClient
import com.microsoft.tfs.core.httpclient.UsernamePasswordCredentials
import com.microsoft.tfs.core.TFSTeamProjectCollection

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

String tfsCollectionName = props['tfsCollectionName']
String tfsPassword = props['tfsPassword']
String tfsUrl = props['tfsUrl']
String tfsUserName = props['tfsUserName']

def currentDirectory = new File(getClass().protectionDomain.codeSource.location.path).parent
System.setProperty("com.microsoft.tfs.jni.native.base-directory", currentDirectory + "/lib/native")

TFSTeamProjectCollection tfsCollection = TFSFactory.createTFSCollection(tfsCollectionName, tfsPassword, tfsUrl, tfsUserName)
def workItemClient = tfsCollection.getWorkItemClient()
Project[] projects = workItemClient.getProjects().getProjects()

Set result = new HashSet()
projects.each {
    result.addAll(it.getWorkItemTypes().getTypes())
}

if (result.size() > 0) {
    MapBuilder mappy = new MapBuilder()
    // Value was originally list of IDs, but length > 256 if many projects exist
    mappy.setIterable(result, 'getName','getName')
    setOutput(apTool, mappy.getJSONString())
}
tfsCollection.close()

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