/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2013. 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

final def workDir = new File('.').canonicalFile
final def airTool = new AirPluginTool(args[0], args[1])
final def props = airTool.getStepProperties()


final def dirOffset = props['dirOffset']
final def xmlFilePath = props['includes']
final def propertyKeys = props['propertyKeys'].split("\n") as List
final def failWithoutMatch = props['failWithoutMatch'].toBoolean()

if (!dirOffset) {
    dirOffset = '.'
}

println "Working Directory: ${workDir}"
println "Directory Offset: ${dirOffset}"
println "File Includes: ${xmlFilePath}"
println "-----------------------------"
def failFlag = false

try {
    def xmlFile = new File(xmlFilePath)
    def root = new XmlSlurper().parseText(xmlFile.getText())

    propertyKeys.each { key ->
        def elementsList = key.split("\\.")
        def desiredElement = root
        for (int i=1; i<elementsList.length; i++) {
            def currentElement = elementsList[i]
            desiredElement = desiredElement."${currentElement}"
        }

        def result = ""
        desiredElement.each {element ->
            if (element.children().size() == 0) {
                if (result) {
                    result = result + "," + element.text()
                }
                else {
                    result = result + element.text()
                }
            }
        }

        if (result.equals("") && failWithoutMatch) {
            failFlag = true
        }

        airTool.setOutputProperty(key, result)
    }

    airTool.setOutputProperties()
}
catch (Exception e) {
    e.printStackTrace()
    System.exit 1
}

if (!failFlag) {
    System.exit(0)
}
else {
    println "Some properties were not found. Exiting Failure"
    System.exit(1)
}
