package com.ociweb.gl.impl.stage;

import com.ociweb.gl.impl.TickListenerBase;
import com.ociweb.pronghorn.pipe.Pipe;
import com.ociweb.pronghorn.stage.PronghornStage;

public class ReactiveManagerPipeConsumer {

	public final Pipe[] inputs;
	private final ReactiveOperator[] operators;
	public final Object behavior;
	

	public ReactiveManagerPipeConsumer(Object behavior, ReactiveOperators operators, Pipe[] inputs) {
		
		this.behavior = behavior;
		this.inputs = inputs;
		assert(PronghornStage.noNulls(inputs));
		this.operators = new ReactiveOperator[inputs.length];
		
		boolean doNotThrow = (behavior instanceof TickListenerBase);
		
		int i = inputs.length;
		while (--i>=0) {
			this.operators[i] = operators.getOperator(inputs[i], doNotThrow);	
		}

	}
	
	public static final void process(ReactiveManagerPipeConsumer that, ReactiveListenerStage r) {
		//only run if one of the inputs has received new data or have data.
		//if (that.newWork.getAndSet(false)) {			
			applyReactiveOperators(that, r, that.inputs, that.behavior, that.operators, that.inputs.length); 
		//}
	}

	private static void applyReactiveOperators(ReactiveManagerPipeConsumer that, ReactiveListenerStage r,
			Pipe[] localInputs, Object localObj, ReactiveOperator[] localOperators, int count) {
		int passes = 0;
		int countDown = -2;
		int temp = 0;
		
		do {
			temp = 0;
			int i = count;
			while (--i >= 0) {
				if (Pipe.isEmpty(localInputs[i]) || !Pipe.hasContentToRead(localInputs[i])) {
					//most calls are stopping on this if
				} else {
					localOperators[i].apply(i, localObj, localInputs[i], r);
					if (Pipe.hasContentToRead(localInputs[i])) {
						temp++;
						passes++;
					}
				}			
			}
			if (-2==countDown) {
				countDown = passes;
			}
		} while (--countDown>=0);
		
		//if (temp>0) {
		//	that.newWork.set(true);
		//}
	}

	/**
	 * A method used to switch old pipe with new pipe if true
	 * @param oldPipe Pipe arg used to determine swap
	 * @param newPipe Pipe arg used to determine swap
	 * @return true if --i> = 0 else false
	 */
	public boolean swapIfFound(Pipe oldPipe, Pipe newPipe) {		
		int i = inputs.length;
		while (--i>=0) {
			if (inputs[i] == oldPipe) {
				inputs[i] = newPipe;
				return true;
			}
		}
		return false;
	}
	
}

@@ -1526,16 +1526,96 @@
  else %7B%0A
+%09%09%09%09%09if (null!=localOperators%5Bi%5D) %7B//skip if null, thisis for the TickListener%0A%09
 %09%09%09%09%09loc
@@ -1669,24 +1669,25 @@
 %5D, r);%0A%09%09%09%09%09
+%09
 if (Pipe.has
@@ -1729,16 +1729,17 @@
 %09%09%09%09
+%09
 temp++;%0A
 %09%09%09%09
@@ -1730,24 +1730,25 @@
 %09%09%09%09temp++;%0A
+%09
 %09%09%09%09%09%09passes
@@ -1747,24 +1747,32 @@
 %09%09passes++;%0A
+%09%09%09%09%09%09%7D%0A
 %09%09%09%09%09%7D%0A%09%09%09%09%7D

add null check for empty operator for tickListener