/* <copyright                                       */
/* notice="cics-lm-source-program"                  */
/* pids="CA0U"                                      */
/* years="2014,2015"                                */
/* crc="1813425462" >                               */
/* 	Licensed Materials - Property of IBM            */
/* 	CA0U                                            */
/* 	(C) Copyright IBM Corp. 2014, 2015 All Rights Reserved. */
/* 	US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp. */
/* </copyright>                                     */
package com.ibm.cics.ucd.steps

import java.text.MessageFormat
import java.util.List;

import com.ibm.cics.core.model.CICSSystemManagerException
import com.ibm.cics.sm.comm.SystemManagerActions
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.model.ICICSObject
import com.ibm.cics.model.ICICSType
import com.ibm.cics.sm.comm.ICICSAction;
import com.ibm.cics.sm.comm.IContext
import com.ibm.cics.ucd.CPSMHelper
import com.ibm.cics.ucd.exceptions.StepFailedException
import com.ibm.cics.ucd.msg.CICSUCDMessage
import com.ibm.cics.ucd.properties.ResourceNameListProperty
import com.ibm.cics.ucd.properties.ResourceNameListPropertySupportWildCard
import com.ibm.cics.ucd.steplabel.CICSUCDStepLabel
import com.urbancode.air.AirPluginTool

abstract class AbstractPerformActionStep extends CICSStep {
	// <copyright 
	// notice="cics-lm-java-class" 
	// pids="CA0U" 
	// years="2014,2015" 
	// crc="1813425462" > 
	static final String COPYRIGHT = "Licensed Materials - Property of IBM CA0U (c) Copyright IBM Corp. 2014, 2015 All Rights Reserved. US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp."; //$NON-NLS-1$
	// </copyright> 

	protected ICICSAction cicsAction


	AbstractPerformActionStep(String inputPropertyFile, String outputPropertyFile) {
		super(inputPropertyFile, outputPropertyFile)
	}

	AbstractPerformActionStep(AirPluginTool apTool) {
		super(apTool)
	}

	/**
	 * Primarily to support unit testing
	 * @param cpsm
	 */
	AbstractPerformActionStep(String inputPropertyFile, String outputPropertyFile, ICPSM cpsm) {
		super(inputPropertyFile, outputPropertyFile)
		this.cpsm = cpsm
	}

	AbstractPerformActionStep(AirPluginTool apTool, ICPSM cpsm) {
		super(apTool)
		this.cpsm = cpsm
	}

	@Override
	protected void runCICSStep(ICPSM cpsm, IContext context) {

		def props = apTool.getStepProperties()
		def cpsmHelper = new CPSMHelper()

		//Resource type is a list from the stepUI or a value specific for a step
		//Get it from abstract method getResourceType(), subclass need to implement this method
		def resourceType = getResourceType(props)
		
		cicsAction = getCicsAction(props)

		//Get the resource type from given property 'resourceType'
		Class<? extends ICICSType<ICICSObject>> typeClass = GenTypeClasses.getCICSTypeClassForResourceTableName(resourceType)
		ICICSType<?> type = typeClass.invokeMethod("getInstance", null)
		
		def resourceNameList = getResourceNameList(cpsmHelper, props, resourceType)
		
		//For step execution status use
		boolean stepFail = false
		int successCount = 0
		int failCount = 0

		//Issue message to start the step execution
		log(MessageFormat.format(CICSUCDMessage.PERFORM, cicsAction.getActionName()))

		//Iterate to discard each resource
		for(int i=0; i < resourceNameList.size(); i++) {
			try {
				//Set a filter for the context
				FilteredContext filteredContext = new FilteredContext(context)
				filteredContext.setAttributeValue(type.NAME, resourceNameList.get(i))

				//Perform action on the resource
				boolean performSuccess = cpsmHelper.performAction(cpsm, type, filteredContext, cicsAction, resourceNameList.get(i))
				if(performSuccess) 
					successCount++

			} catch (CICSSystemManagerException e) {
				//Any exception thrown in the perform process handled here
				failCount++
				stepFail = true
				cpsmHelper.handleException(e, resourceType, cicsAction, resourceNameList.get(i))
			}

		}

		log(MessageFormat.format(CICSUCDMessage.resultSummary, cicsAction.getActionName(), Integer.toString(successCount), Integer.toString(failCount)))

		if (stepFail) {
			throw new StepFailedException("Step failed.");
		}
	}
	
	protected String getResourceType(Properties props){
		return props[RESOURCE_TYPE]
	}

	protected ICICSAction getCicsAction(Properties props) {
		return SystemManagerActions.(props[ACTION_TYPE]);
	}
	
	protected List<String> getResourceNameList(CPSMHelper cpsmHelper, Properties props, String resourceType) {		
		return new ResourceNameListPropertySupportWildCard(CICSUCDStepLabel.RESOURCE_NAME_LIST, resourceType, cpsmHelper.isNameCaseSensitive(resourceType), true).parse(props['resourceNameList']).getValue()
		
	}

}
