import com.urbancode.air.*
import com.urbancode.air.plugin.automation.*


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

final String serverUrl = props['tfsUrl']
final String serverUserName = props['tfsUsername']
final String serverPassword = props['tfsPassword']
final String tfsVersion = props['tfsVersion']

final String workItemId = props['workItemId']?:''
final String fields = props['fields']
final String requestId          = props['requestId']
final String appProcId          = props['appProcId']
final String compProcId         = props['compProcId']
final String procId             = props['procId']
final String urlFieldName       = props['urlFieldName']
final String deployUrl          = props['deployUrl']
def procRequestScope = ""

UpdateWorkItem uwi = new UpdateWorkItem()
uwi.serverUrl = serverUrl
uwi.serverUserName = serverUserName
uwi.serverPassword = serverPassword
uwi.tfsVersion = tfsVersion

uwi.workItemId = workItemId
uwi.fields = fields

if (urlFieldName) {
    if (compProcId && compProcId != "\${p:componentProcess.id}") {
        procRequestScope = "#componentProcessRequest"
    }
    else if (appProcId && appProcId != "\${p:applicationProcess.id}") {
        procRequestScope = "#applicationProcessRequest"
    }
    else if (procId && procId != "\${p:process.id}") {
        procRequestScope = "#processRequest"
    }
    if (procRequestScope) {
        deployUrl = deployUrl + "/${procRequestScope}/${requestId}"
        def urlComment = " IBM UrbanCode Deploy Process Execution: ${deployUrl}"
        uwi.fields = uwi.fields + "\nAPPEND:${urlFieldName}:${urlComment}"
    }
}

uwi.execute()

