package com.infoteria.asteria.flowlibrary2.component.control;

import com.infoteria.asteria.flowengine2.EngineConstant;
import com.infoteria.asteria.flowengine2.execute.ExecuteContext;
import com.infoteria.asteria.flowlibrary2.FlowException;
import com.infoteria.asteria.flowlibrary2.component.ComponentException;
import com.infoteria.asteria.flowlibrary2.component.SimpleComponent;
import com.infoteria.asteria.flowlibrary2.stream.StreamDataObject;
import com.infoteria.asteria.flowlibrary2.stream.StreamType;
import com.infoteria.asteria.flowlibrary2.property.IntegerProperty;

public class LoopStartComponent extends SimpleComponent {
	
	public static final String COMPONENT_NAME = "LoopStart";
	public String getComponentName() { return COMPONENT_NAME;}
	public String getLicenseStr() { return EngineConstant.LICENSE_CORE; }

	private static final String INVALID_LOOP_COUNT = "1";
	
	private IntegerProperty _loopCount = new IntegerProperty("LoopCount", true, true, 1);
	private int _count;

	private StreamDataObject _outputStream;

	public LoopStartComponent() {
		getInputConnector().setAcceptType(StreamType.ALL);
		getInputConnector().setAcceptLinkCount(1);
		getOutputConnector().setAcceptType(StreamType.ALL);
		
		registerProperty(_loopCount);
	}

	public boolean loopPossibility() {
		return true;
	}
	
	@SuppressWarnings("deprecation")
	public boolean execute(ExecuteContext context) throws FlowException {
		_count = _loopCount.intValue();
		if (_count <= 0)
			throw new ComponentException(getMessage(INVALID_LOOP_COUNT, Integer.toString(_count)));
		
		_count--;
		_outputStream = passStreamAndReturn();
		if (_count == 0) {
			_outputStream = null;
			return true;
		} else {
			return false;
		}
	}
	
	public int executeLoop(ExecuteContext context) throws FlowException {
		_count--;
		getOutputConnector().setStream(_outputStream);
		if (_count == 0) {
			_outputStream = null;
			return LOOP_END;
		} else {
			return LOOP_CONTINUE;
		}
	}
}
