/*
* 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.plugins.autoscaler

import groovy.json.JsonSlurper
import java.lang.RuntimeException

public class JSONHelper {

    /*
     * 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 JSON. String JSON text is returned.
     *
     * param input  File or text that contains JSON
     * result       Returns confirmed JSON string
     */
    public static String getJSONText(String input) {
        def jsonResult
        File file = new File(input)
        // Check if the given path exists
        if (file.isFile()) {
            // Retrieve file text
            jsonResult =  file.getText()
            println "[Ok] JSON input is recognized as a file: ${input}."
        }
        else {
            // Else, the given text isn't a file
            jsonResult = input
            println "[Ok] JSON input is recognized as text."
        }
        println "JSON Input:"
        println jsonResult
        println ""

        // Confirm gathered input is JSON, else catch and fail
        try {
            JsonSlurper sluper = new JsonSlurper()
            sluper.parseText(jsonResult)
        }
        catch (RuntimeException ex) {
            println " "
            println "[Error] JSON input is invalid. Please review the JSON format or file path."
            println ex
            System.exit(1)
        }
        return jsonResult
    }
}