/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2016. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/

package com.urbancode.air.plugin.bigfix

import groovy.util.XmlSlurper
import org.xml.sax.SAXException

public class TextBoxHelper {

    /*
     * Reads input. Determine if file or text. If file, it will try to read from the file, and
     * retrieve its contents. Then confirm that the given text is XML. String XML text is returned.
     *
     * param input  File or text that contains XML
     * result       Returns confirmed XML string
     */
    public String getXMLText(String input) {
        def xmlResult
        File file = new File(input)
        // Check if the given path exists
        if (file.isFile()) {
            // Retrieve file text
            xmlResult =  file.getText()
            println "[Ok]  XML input is recognized as a file: ${input}."
        }
        else {
            // Else, the given text isn't a file
            xmlResult = input
            println "[Ok]  XML input is recognized as text."
        }
        println "Discovered XML:"
        println xmlResult

        // Confirm gathered input is XML, else catch and fail
        try {
            XmlSlurper sluper = new XmlSlurper()
            sluper.parseText(xmlResult)
        }
        catch (IOException ex) {
            throw new IOException ("[Error]  XML input is invalid. Please review the XML format: ${ex.getMessage()}.")
        }
        catch (SAXException ex) {
            throw new SAXException ("[Error]  XML input is invalid. Please review the XML format: ${ex.getMessage()}.")
        }
        return xmlResult
    }
}