/* <copyright                                       */
/* notice="cics-lm-source-program"                  */
/* pids="CA0U"                                      */
/* years="2014"                                     */
/* crc="2800743495" >                               */
/* 	Licensed Materials - Property of IBM            */
/* 	CA0U                                            */
/* 	(C) Copyright IBM Corp. 2014 All Rights Reserved. */
/* 	US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp. */
/* </copyright>                                     */
import com.ibm.cics.core.model.CICSCore
import com.ibm.cics.core.model.CICSSystemManagerException;
import com.ibm.cics.core.model.Context
import com.ibm.cics.core.model.FilteredContext
import com.ibm.cics.core.model.GenTypeClasses
import com.ibm.cics.core.model.ICPSM
import com.ibm.cics.core.model.ProgramType
import com.ibm.cics.core.model.ProgramDefinitionType
import com.ibm.cics.core.model.ScopedContext
import com.ibm.cics.model.ICICSAttribute
import com.ibm.cics.model.ICICSType
import com.ibm.cics.model.ICICSObject
import com.ibm.cics.sm.comm.IContext
import com.ibm.cics.sm.comm.IResourceErrorCode
import com.ibm.cics.sm.comm.ISystemManagerResponseValues
import com.ibm.cics.sm.comm.SystemManagerActions
import com.ibm.cics.sm.comm.SystemManagerConnectionException
import com.ibm.cics.sm.comm.sm.SMConnection
import com.urbancode.air.AirPluginTool

import java.util.logging.LogManager
import java.util.logging.Logger
import java.util.logging.Handler
import java.util.logging.Level

import com.ibm.cics.ucd.CMCIConnectionHelper
import com.ibm.cics.ucd.CPSMHelper
import com.ibm.cics.ucd.JuliToLog4jHandler
import com.ibm.cics.ucd.properties.CommonCICSNameProperty
import com.ibm.cics.ucd.properties.LongProperty
import com.ibm.cics.ucd.properties.ResourceNameListProperty
import com.ibm.cics.ucd.steplabel.CICSUCDStepLabel
import com.ibm.cics.ucd.msg.CICSUCDMessage

import java.text.MessageFormat

Logger rootLogger = LogManager.getLogManager().getLogger("")
// Remove any old handlers
for (Handler handler : rootLogger.getHandlers()) {
	rootLogger.removeHandler(handler)
}

// Create our own logger
comIbmCicsLogger = Logger.getLogger("com.ibm.cics")
comIbmCicsLogger.setUseParentHandlers(false)

// Pass all events on
Level handlerLevel = Level.ALL;
Level rootLevel = Level.ALL

// Add our own handler to JUL
Handler activeHandler = new JuliToLog4jHandler()
activeHandler.setLevel(handlerLevel)
comIbmCicsLogger.addHandler(activeHandler)
rootLogger.setLevel(rootLevel)

/* This gets us the plugin tool helper.
 * This assumes that args[0] is input props file and args[1] is output props file.
 * By default, this is true. If your plugin.xml looks like the example.
 * Any arguments you wish to pass from the plugin.xml to this script that you don't want to
 * pass through the step properties can be accessed using this argument syntax
 */
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()

//--------------------- step logic ---------------------
final def resourceGroupNameList = new ResourceNameListProperty(CICSUCDStepLabel.RESOURCE_NAME_LIST, true).parse(props['resourceDescriptionNameList']).getValue()

//Establish CMCI Connection
def CMCIConnectionHelper connHelper = new CMCIConnectionHelper(props)
SMConnection conn = connHelper.establishCMCIConnection()

//For step execution status use
stepFail = false
successCount = 0
failCount = 0

//Get cpsm object
ICPSM cpsm = CICSCore.getCPSM()
cpsm.setConnection(conn)

//First check if connection is a CPSM environment
if (!connHelper.isCICSplex(conn)) {
	System.out.println(MessageFormat.format(CICSUCDMessage.notCPSMEnv))
	stepFail = true
	System.exit(1)
}

//Get context form connHelper
IContext context = connHelper.getContext(conn)

//Get the resource type for resource group
Class<? extends ICICSType<ICICSObject>> typeClass = GenTypeClasses.getCICSTypeClassForResourceTableName('RESDESC')
ICICSType<?> type = typeClass.invokeMethod("getInstance", null)

//Issue message to start the step execution
System.out.println(MessageFormat.format(CICSUCDMessage.installfromDREP))

//Iterate to install each resource
for(int i=0; i < resourceGroupNameList.size(); i++)

{
	def cpsmHelper = new CPSMHelper()
	try {
		//Invoke specific method to install the resource
		if(cpsmHelper.installResDescription(cpsm, type, context, SystemManagerActions.Install, resourceGroupNameList.get(i)))
		{
			successCount++
		}

	} catch (CICSSystemManagerException e) {
		failCount++
		stepFail = true
		//Any exception thrown in the install process handled here
		cpsmHelper.handleInstallException(e, 'RESDESC',resourceGroupNameList.get(i))

	}
}

//Print the summary
System.out.println(MessageFormat.format(CICSUCDMessage.resultSummary, CICSUCDMessage.install, Integer.toString(successCount), Integer.toString(failCount)))

if(stepFail)
	System.exit(1)
else
	System.exit(0)
