package ru.r2cloud.jradio.aausat4;

import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;

import ru.r2cloud.jradio.blocks.TaggedStreamToPdu;
import ru.r2cloud.jradio.fec.ccsds.Randomize;
import ru.r2cloud.jradio.fec.ccsds.ReedSolomon;
import ru.r2cloud.jradio.fec.ccsds.Viterbi;

public class AAUSAT4 implements Iterable<AAUSAT4Beacon>, Iterator<AAUSAT4Beacon>, Closeable {

	private final TaggedStreamToPdu input;
	private byte[] current;

	public AAUSAT4(TaggedStreamToPdu input) {
		this.input = input;
	}

	@Override
	public Iterator<AAUSAT4Beacon> iterator() {
		return this;
	}

	@Override
	public boolean hasNext() {
		try {
			current = input.readBytes();
			if (current != null && current.length != 0) {
				return true;
			} else {
				return false;
			}
		} catch (IOException e) {
			return false;
		}
	}

	@Override
	public AAUSAT4Beacon next() {
		if (current[0] == 0x59) {
			// long frame
			byte[] viterbi = Viterbi.decode(Arrays.copyOfRange(current, 1, 250));
			byte[] deShuffled = Randomize.shuffle(viterbi);
			byte[] rawData = ReedSolomon.decode(deShuffled);
			try {
				AAUSAT4Beacon result = new AAUSAT4Beacon();
				result.readExternal(rawData);
				return result;
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		} else if (current[0] == 0xA6) {
			// short frame
		} else {
			throw new IllegalArgumentException("invalid frame start: " + current[0]);
		}
		return null;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}

	@Override
	public void close() throws IOException {
		input.close();
	}
}

@@ -125,24 +125,72 @@
 va.util.
-Iterator
+HashSet;%0Aimport java.util.Iterator;%0Aimport java.util.Set
 ;%0A%0Aimpor
@@ -533,16 +533,172 @@
 current;
+%0A%09private final static Set%3CByte%3E supportedFormats = new HashSet%3C%3E();%0A%0A%09static %7B%0A%09%09supportedFormats.add((byte) 0x59);%0A%09%09supportedFormats.add((byte) 0xA6);%0A%09%7D
 %0A%0A%09publi
@@ -959,16 +959,57 @@
 gth != 0
+ && supportedFormats.contains(current%5B0%5D)
 ) %7B%0A%09%09%09%09
@@ -1582,24 +1582,24 @@
  == 0xA6) %7B%0A
+
 %09%09%09// short 
@@ -1608,96 +1608,8 @@
 ame%0A
-%09%09%7D else %7B%0A%09%09%09throw new IllegalArgumentException(%22invalid frame start: %22 + current%5B0%5D);%0A
 %09%09%7D%0A

return false instead of throwing error on next()