package innovimax.mixthem.io;

import java.io.IOException;
import java.util.ArrayList;
//import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.IntStream;

public class MultiChannelCharReader implements IMultiChannelCharInput {
	
	private final List<ICharInput> readers = new ArrayList<ICharInput>();
	
	/**
	* Constructor
	* @param inputs The list of inputs as InputResource
	* @param selection The input index selection (maybe empty)
	* @see innovimax.mixthem.io.InputResource
	*/
	public MultiChannelCharReader(final List<InputResource> inputs, final Set<Integer> selection) {		
		IntStream.rangeClosed(1, inputs.size())
			.filter(index -> selection.isEmpty() || selection.contains(Integer.valueOf(index)))
			.mapToObj(index -> inputs.get(index-1))
			.forEachOrdered(input -> {
				try {
					this.readers.add(new DefaultCharReader(input));
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			});
	}
	
	@Override
	public boolean hasCharacter() throws IOException {
		return this.readers.stream()
			.anyMatch(reader -> {
				try {
					return reader.hasCharacter();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}		
			});
	}
	
	@Override
	public int[] nextCharacterRange() throws IOException {
		final int[] chars = new int[this.readers.size()];
		/*int channel = 0;
		final Iterator<ICharInput> iterator = this.readers.iterator();
		while (iterator.hasNext()) {
			final ICharInput reader = iterator.next();
			final int c = reader.nextCharacter();
			chars[channel++] = c;
		}*/
		IntStream.range(0, readers.size())
			.forEachOrdered(index -> {
				try {
					chars[index] = readers.get(index).nextCharacter();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			});
		return chars;
	}

	@Override
	public void close() throws IOException {
		this.readers.forEach(reader -> {
			try {
				reader.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		});
	}
	
}

@@ -1284,16 +1284,18 @@
 ion %7B%0A%09%09
+/*
 final in
@@ -1340,243 +1340,8 @@
 )%5D;%0A
-%09%09/*int channel = 0;%0A%09%09final Iterator%3CICharInput%3E iterator = this.readers.iterator();%0A%09%09while (iterator.hasNext()) %7B%0A%09%09%09final ICharInput reader = iterator.next();%0A%09%09%09final int c = reader.nextCharacter();%0A%09%09%09chars%5Bchannel++%5D = c;%0A%09%09%7D*/%0A
 %09%09In
@@ -1548,16 +1548,16 @@
 %0A%09%09%09%7D);%0A
-
 %09%09return
@@ -1563,16 +1563,204 @@
 n chars;
+*/%0A%09%09return readers.stream()%0A%09%09%09.map(reader -%3E %7B%0A%09%09%09%09try %7B%0A%09%09%09%09%09return reader.nextCharacter();%0A%09%09%09%09%7D catch (IOException e) %7B%0A%09%09%09%09%09throw new RuntimeException(e);%0A%09%09%09%09%7D%09%0A%09%09%09%7D)%0A%09%09%09.toArray();
 %0A%09%7D%0A%0A%09@O

Update MultiChannelCharReader.java