package innovimax.mixthem.operation;

import innovimax.mixthem.MixException;
import innovimax.mixthem.arguments.RuleParam;
import innovimax.mixthem.arguments.ParamValue;

import java.util.Arrays;
import java.util.Map;
import java.util.Random;

/**
* <p>Alternate two or more bytes.</p>
* @see IByteOperation
* @author Innovimax
* @version 1.0
*/
public class DefaultByteAlternation extends AbstractByteOperation {
	
	private final AltMode mode;
	private int channel;
	private final Random random;	
	
	/**
	* Constructor
	* @param mode The alternate mode to process
 	* @param params The list of parameters (maybe empty)
	* @see innovimax.mixthem.arguments.RuleParam
	* @see innovimax.mixthem.arguments.ParamValue
	*/
	public DefaultByteAlternation(final AltMode mode, final Map<RuleParam, ParamValue> params) {
		super(params);
		this.mode = mode;
		this.channel = 0;
		this.random = new Random(params.getOrDefault(RuleParam.RANDOM_SEED, AltOperation.DEFAULT_RANDOM_SEED.getValue()).asInt());
	}
	
	@Override
	public void process(byte[] bytes, ByteResult result) throws MixException {
		result.reset();
		final int[] array = new int[1];
		int channel = this.mode == AltMode.NORMAL ? this.channel : this.random.nextInt(bytes.length);
		byte b = bytes[channel];
		System.out.println("BYTES+"+Arrays.toString(bytes)+" CHANNEL="+channel+" BYTE="+b);
		if (b == -1) {					
			channel = nextChannel(bytes, channel);
			b = bytes[channel];
			System.out.println("NEW_CHANNEL="+channel+" BYTE="+b);
		}
		array[0] = b;
		if (this.mode == AltMode.NORMAL) {
			this.channel = channel + 1;
			if (this.channel == bytes.length) {
				this.channel = 0;
			}		
		}
		result.setResult(Arrays.stream(array));
	}
	
	private int nextChannel(final byte[] bytes, final int channel) {
		int c = channel+1;
		while (c != channel) {
			if (c < bytes.length) {
				final byte b = bytes[c];
				if (b != -1) {
					break;
				}
				c++;
			} else {
				c = 0;
			}
		}
		return c;
	}

}

@@ -1034,17 +1034,21 @@
 e%5B%5D byte
-s
+Range
 , ByteRe
@@ -1215,25 +1215,29 @@
 nextInt(byte
-s
+Range
 .length);%0A%09%09
@@ -1241,33 +1241,37 @@
 %0A%09%09byte b = byte
-s
+Range
 %5Bchannel%5D;%0A%09%09Sys
@@ -1402,17 +1402,21 @@
 nel(byte
-s
+Range
 , channe
@@ -1430,17 +1430,21 @@
 b = byte
-s
+Range
 %5Bchannel
@@ -1615,25 +1615,29 @@
 nnel == byte
-s
+Range
 .length) %7B%0A%09
@@ -1757,17 +1757,21 @@
 e%5B%5D byte
-s
+Range
 , final 
@@ -1771,24 +1771,27 @@
  final int c
+urC
 hannel) %7B%0A%09%09
@@ -1795,20 +1795,29 @@
 %0A%09%09int c
+hannel
  = c
+urC
 hannel+1
@@ -1832,13 +1832,22 @@
 e (c
+hannel
  != c
+urC
 hann
@@ -1864,16 +1864,26 @@
 f (c
+hannel
  %3C byte
-s
+Range
 .len
@@ -1916,11 +1916,21 @@
 byte
-s%5Bc
+Range%5Bchannel
 %5D;%0A%09
@@ -1970,16 +1970,22 @@
 %09%7D%0A%09%09%09%09c
+hannel
 ++;%0A%09%09%09%7D
@@ -1997,16 +1997,22 @@
  %7B%0A%09%09%09%09c
+hannel
  = 0;%0A%09%09
@@ -2028,16 +2028,22 @@
 return c
+hannel
 ;%0A%09%7D%0A%0A%7D%0A

Update DefaultByteAlternation.java