/*
 * 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 com.urbancode.air.AirPluginTool
import com.urbancode.air.FileSet
import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory


import javax.xml.xpath.XPath
import javax.xml.xpath.XPathConstants
import javax.xml.xpath.XPathExpression
import javax.xml.xpath.XPathFactory
import groovy.transform.Field
import org.w3c.dom.Document

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

final def srcDirOffset = props['srcDirOffset']
final def xmlFile = props['xmlFile']
final def xpath = props['xPath']

def data

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

while (srcDirOffset.endsWith(File.separator)) {

    srcDirOffset.subset(0, srcDirOffset.length() -1)
}

while (srcDirOffset.startsWith(File.separator)) {

    srcDirOffset.subset(1)
}

println "Working Directory: ${workDir}"
println "Source Directory Offset: ${srcDirOffset}"
println "Xml File: ${xmlFile}"
println "-----------------------------"

try {

    def file = workDir.getCanonicalPath() + File.separator + srcDirOffset + File.separator + xmlFile

    if (!new File (file).isFile()) {
        println "File ${file} doesn't exist!"
        System.exit 1
    }

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance()
    DocumentBuilder builder = factory.newDocumentBuilder()
    Document doc = builder.parse(file)
    XPathFactory xPathfactory = XPathFactory.newInstance()
    XPath xPath = xPathfactory.newXPath()
    XPathExpression expr = xPath.compile(xpath)
    data = expr.evaluate(doc, XPathConstants.STRING)

    if (data) {
        println "Data referred by xpath  : ${data}"
        airTool.setOutputProperty("xmlNodeText", data)
    }else {
        println "Element not found!"
        System.exit 1
    }
}
catch (Exception e) {

    e.printStackTrace()
    System.exit 1
} finally {

    airTool.setOutputProperty("xmlNodeText", data)
    airTool.setOutputProperties()
}

System.exit(0)
