/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* UrbanCode Build
* UrbanCode Release
* AnthillPro
* (c) Copyright IBM Corporation 2011, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/
import groovy.util.slurpersupport.Attribute;

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 instanceof Attribute || 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)
}
