#!/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.NodeParser
import com.urbancode.air.plugin.tfs.TFSFactory
import com.urbancode.air.plugin.tfs.MapBuilder

import com.microsoft.tfs.core.clients.workitem.fields.*
import com.microsoft.tfs.core.clients.workitem.node.*
import com.microsoft.tfs.core.clients.workitem.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 projects = tfsCollection.getWorkItemClient().getProjects()
Project[] allProjects = projects.getProjects()

NodeParser iterationNodeHelper = new NodeParser()

projects.each {
    rootNodes = it.getIterationRootNodes().getNodes()
    iterationNodeHelper.parseNodes(rootNodes)
}

setOutput(apTool, iterationNodeHelper.getJSONString())

tfsCollection.close()

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