/*
 * Copyright 2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.batch.core.jsr.step;

import java.util.Collection;

import javax.batch.api.Decider;
import javax.batch.operations.BatchRuntimeException;

import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.step.AbstractStep;

/**
 * Implements a {@link Step} to follow the rules for a decision state
 * as defined by JSR-352.  Currently does not support the JSR requirement
 * to provide all of the last {@link javax.batch.runtime.StepExecution}s from
 * a split.
 *
 * @author Michael Minella
 * @since 3.0
 */
public class DecisionStep extends AbstractStep {

	private final Decider decider;

	/**
	 * @param decider a {@link Decider} implementation
	 */
	public DecisionStep(Decider decider) {
		this.decider = decider;
	}

	@Override
	protected void doExecute(StepExecution stepExecution) throws Exception {
		Collection<StepExecution> stepExecutions = stepExecution.getJobExecution().getStepExecutions();

		// Used to determine if this step is the first step in the job (not allowed)
		if(stepExecutions.size() == 1) {
			stepExecution.setTerminateOnly();
			throw new BatchRuntimeException("Decision not a valid first step");
		}

		// Currently does not support splits
		StepExecution lastExecution = null;

		if(stepExecutions != null) {
			for (StepExecution curStepExecution : stepExecutions) {
				if(lastExecution == null || (curStepExecution.getEndTime() != null && curStepExecution.getEndTime().after(lastExecution.getEndTime()))) {
					lastExecution = curStepExecution;
				}
			}
		}

		javax.batch.runtime.StepExecution [] executions = new org.springframework.batch.core.jsr.StepExecution[1];

		executions[0] = new org.springframework.batch.core.jsr.StepExecution(lastExecution);

		try {
			ExitStatus exitStatus = new ExitStatus(decider.decide(executions));

			stepExecution.getJobExecution().setExitStatus(exitStatus);
			stepExecution.setExitStatus(exitStatus);
		} catch (Exception e) {
			stepExecution.setTerminateOnly();
			stepExecution.addFailureException(e);
			throw e;
		}
	}
}
