import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.jboss.helper.JBossHelper

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

final def isWindows = apTool.isWindows

def jbossPath = props['jbosspath']
def name = props['name']
def entries = props['entries']
def connector = props['connector'].split(",") as List
def profile = props['profile']
def cli = isWindows ? "jboss-cli.bat" : "jboss-cli.sh"
def controller = props['controller'] != null ? props['controller'] : ""

def pathFile = new File(jbossPath)
def cliFile = new File(pathFile, cli)

if (!cliFile.isFile()) {
    executable = isWindows ? "jboss-admin.bat" : "jboss-admin.sh"
    cliFile = new File(pathFile, executable)
    
    if (!cliFile.isFile()) {
        throw new Exception("Could not find JBoss executable")
    }
}

def cmdArgs = [cliFile.absolutePath]

if (controller?.trim()?.size() > 0) {
    cmdArgs << "--controller=${controller}"
}

def helper = new JBossHelper(cmdArgs)

def scriptData = helper.createTempFile()

scriptData.withWriter { out ->
    out  << "connect\n"
    out  << "connection-factory add --name=${name} --entries=${entries} --connector={\"${connector[0]}\"=>"

    if (connector.size() > 1) {
        def connectCount = 0
        out  << "["
        for (connection in connector) {
            out  << "\"${connection}\""
            connectCount++
            if (connectCount < connector.size()) {
                out  << ","
            }
        }
        out  << "]"
    }
    else {
        out  << "undefined"
    }

    out  << "}"

    if (profile?.trim()?.size() > 0) {
        out  << " --profile=${profile}"
    }
}

cmdArgs << "--file=${scriptData.absolutePath}"

helper.runFactoryCommand("Adding factory to JBoss")

System.exit(0)
