/*
 * Licensed Materials - Property of IBM* and/or HCL**
 * UrbanCode Build
 * (c) Copyright IBM Corporation 2013, 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 java.nio.charset.Charset

import groovy.json.JsonOutput

import com.urbancode.air.AirPluginTool
import com.urbancode.air.CommandHelper

def apTool = new AirPluginTool(this.args[0], this.args[1])

def props = apTool.getStepProperties()

def jsonContents  = props['jsonTextArea']
final def fileName = props['file']
final def beautifyJSON = props['beautifyJSON']?.toBoolean()
final def overwrite = props['overwrite']?.toBoolean()
String customEncoding = props['customEncoding']?.trim()

final def workDir = new File('.').canonicalFile

try {
    Charset encodingToUse = null;
    Charset defaultEncoding = Charset.forName(System.getenv("DS_SYSTEM_ENCODING"));
    if (customEncoding) {
        encodingToUse = Charset.forName(customEncoding);
    } else {
        encodingToUse = defaultEncoding;
    }

    File file = new File(workDir, fileName).getCanonicalFile();
    if (file.exists() && !overwrite) {
        println "File $file already exists!"
        System.exit 1
    }
    else {
        println "Using file encoding " + encodingToUse.name()

        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file), encodingToUse);
        if (beautifyJSON) {
            jsonContents = JsonOutput.prettyPrint(jsonContents)
            println "The beautified json:" + JsonOutput.prettyPrint(jsonContents)
        }
        outputStreamWriter.write(jsonContents)
        outputStreamWriter.close()

        println "Successfully ${overwrite ? 'replaced' : 'created'} file $file"
        if (encodingToUse.equals(defaultEncoding)) {
            println "Wrote the following content to the file:"
            println jsonContents
        } else {
            println "Content has been written to the file. Cannot preview written contents because system encoding and the specified custom file encoding differ."
        }
    }
}
catch (Exception e) {
    println "Error creating file $fileName: ${e.message}"
    System.exit(1)
}

System.exit(0)

