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.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;
	
	public LoopStartComponent() {
		getInputConnector().setAcceptType(StreamType.ALL);
		getInputConnector().setAcceptLinkCount(1);
		getOutputConnector().setAcceptType(StreamType.ALL);
		
		registProperty(_loopCount);
	}
	
	public boolean loopPossibility() {
		return true;
	}
	
	public boolean execute(ExecuteContext context) throws FlowException {
		_count = _loopCount.intValue();
		if (_count <= 0)
			throw new ComponentException(getMessage(INVALID_LOOP_COUNT, Integer.toString(_count)));
		
		_count--;
		passStream();
		return _count == 0;
	}
	
	public int executeLoop(ExecuteContext context) throws FlowException {
		_count--;
		passStream();
		return _count == 0 ? LOOP_END : LOOP_CONTINUE;
	}
	
}
