package org.kne.cloud.network.perf;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

import org.kne.cloud.network.ByteBufferAllocator;
import org.kne.cloud.network.NetworkPacket;
import org.kne.cloud.network.klalb.KLALBPacket;

public class TESTNPacket extends KLALBPacket {
	
	private static final int HEADER_LENGTH=3;
	
	private ByteBuffer dataBuffer;//=NetworkPacket.databufferpool_65535.borrow();
	@Override
	public long getTotalLength() {
		return HEADER_LENGTH+dataBuffer.limit();
	}


	public TESTNPacket(int limit) {
		super(TESTN,HEADER_LENGTH);
		//dataBuffer.limit(limit);
		dataBuffer=NetworkPacket.bufferAllocator.allocate(limit);
	}

	

	public ByteBuffer getDataBuffer() {
		return dataBuffer;
	}


	@Override
	public void writeToChannel(WritableByteChannel dto) throws IOException {
		klalbHeader.putChar(1, (char) dataBuffer.limit());
		super.writeToChannel(dto);
		//System.out.println(dataBuffer);
		dto.write(dataBuffer.slice(0, dataBuffer.limit()));
	}

	@Override
	public void readFromChannel(ReadableByteChannel din) throws IOException {
		super.readFromChannel(din);
		int limit=klalbHeader.getChar(1);
		dataBuffer=NetworkPacket.bufferAllocator.allocate(limit);
		 while(dataBuffer.hasRemaining()){
			if(din.read(dataBuffer)==-1) {
				throw new EOFException();
			}
		}
		 dataBuffer.flip();
	}

	public TESTNPacket(ByteBuffer bb) {
		super(bb,HEADER_LENGTH);
	}


	@Override
	public String toString() {
		return "TESTN["+dataBuffer.limit()+"]";
	}

	
}
