package aalg.mailer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.Channels;

import aalg.algebra.Utils;

public abstract class ChannelConnection<CH extends ByteChannel> {

	private enum ReadState {
		LENGTH,
		CONTENT
	};
	
	private static final int LENGTH_SIZE = 8;
	
	protected final CH channel;
	protected ByteBuffer inputBuffer;
	protected ByteBuffer outputBuffer;
	private ReadState readState;
	
	protected ChannelConnection (final CH channel) {
		this.channel = channel;
		
		setLengthState();
	}
	
	private void setLengthState() {
		this.readState = ReadState.LENGTH;
		this.inputBuffer = ByteBuffer.allocate(LENGTH_SIZE);
	}

	public void readData() throws IOException {
		channel.read(inputBuffer);
	}
	
	public void writeBlock (final byte[] blockData) throws IOException {
		final ByteArrayOutputStream stream = new ByteArrayOutputStream();
		Utils.writeLong(blockData.length, stream, LENGTH_SIZE);
		stream.write(blockData);
		
		outputBuffer = ByteBuffer.wrap(stream.toByteArray());
	}
}
