/*
* 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.ibm.urbancode.zos.common.TSOHelper;
import com.urbancode.air.AirPluginTool

import static java.lang.Integer.valueOf

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

	/* Here we call getStepProperties() to get a Properties object that contains the step properties
	 * provided by the user. 
	 */
	def props = apTool.getStepProperties();

	//set up working directory
	def workDir = new File(".").canonicalFile;
	def pluginHome = System.getenv("PLUGIN_HOME");
	def dirOffset = props['dirOffset'];

	// verify parameters
	def dataSetName = props['dataSetName']
	if (dataSetName && !(dataSetName =~ /^\s*$/)) {
		dataSetName = dataSetName.trim()
	} else {
		throw new InvalidPropertiesFormatException("Dataset Name can not be empty.")
	}
	def volumeSerial = props['volumeSerial']
	if (volumeSerial) {
		volumeSerial = volumeSerial.trim()
		if (!(volumeSerial ==~ /^[\w|\d]{6}$/)) {
			throw new InvalidPropertiesFormatException("The format of volumeSerial is not supported")
		}
	}

	def spaceUnit = props['spaceUnit']

	def averageRECUnit = props['averRecUnit']

	int primaryQuantity = valueOf(props['primaryQuantity'] as String)

	int secondaryQuantity = valueOf(props['secondaryQuantity'] as String)

	def directoryBlocksStr = props['directoryBlocks']
	def directoryBlocks = null
	if (directoryBlocksStr) {
		directoryBlocks = valueOf(directoryBlocksStr.trim())
	}

	def recordFormat = props['recordFormat']

	int recordLength = valueOf(props['recordLength'] as String)

	int blockSize = valueOf(props['blockSize'] as String)

	def dataSetNameType = props['dataSetNameType'];

	// generate command

    def cmd = "ALLOCATE DATASET(" + dataSetName + ") NEW "

    if (volumeSerial) {
        cmd += "VOLUME($volumeSerial) "
    }
    cmd += "SPACE($primaryQuantity ,$secondaryQuantity) "

    switch (spaceUnit) {
		case "TRACKS":
		case "CYLINDERS":
            cmd += "$spaceUnit ";
            break;
        case "BLKS":
            cmd += "BLOCK($recordLength) "
            break;
    }
    if (!blockSize.equals(0)){
        cmd += "BLKSIZE($blockSize) "
    }

    if (!averageRECUnit.equals("---")) {
        cmd += "AVGREC($averageRECUnit) "
    }

    if (directoryBlocks && directoryBlocks > 0) {
        cmd += "DIR($directoryBlocks) "
    }

    cmd += "RECFM(${recordFormat}) "

    if (!spaceUnit.equals("BLKS") || !recordFormat.equals("U")) {
        cmd += "LRECL($recordLength) "
    }

    if (dataSetNameType && !dataSetNameType.equals("---")) {
        cmd += "DSNTYPE($dataSetNameType) "
    }

    //execute command
	println "Allocate Comand:"+cmd
	
	def tsoHelper = new TSOHelper()
	try{
		tsoHelper.runCommandFromUSS(cmd);
	}
	catch (Exception e) {
			println "Error executing TSO/ISPF command: ${e.message}";
			e.printStackTrace();
			System.exit(1);
	}
	
	if (tsoHelper.returnCode > 0) {
		println tsoHelper.errorText;
	}
	println tsoHelper.outputText
	
	println "The program terminated with return code "+ tsoHelper.returnCode
	//Set an output property
	apTool.setOutputProperty("returnCode", tsoHelper.returnCode.toString());
	
	apTool.storeOutputProperties();//write the output properties to the file
}catch (Exception e) {
		println "Error allocating data set: ${e.message}";
		e.printStackTrace();
		System.exit(1);
}

System.exit(0);