package org.kne.cloud.network;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;

public class PacketSpliter {
	private volatile int splitSize;
	private AtomicInteger series=new AtomicInteger();
	private WritableByteChannel writableChannel;
	public PacketSpliter(WritableByteChannel writableChannel,int splitSize) {
		this.writableChannel=writableChannel;
		this.splitSize=splitSize;
	}

	public int getSplitSize() {
		return splitSize;
	}

	
	
	public WritableByteChannel getWritableChannel() {
		return writableChannel;
	}

	public void setSplitSize(int splitSize) {
		this.splitSize = splitSize;
	}

	@Override
	public String toString() {
		return "PacketSpliter [splitSize=" + splitSize + "]";
	}
	
	public void write(ByteBuffer bb) throws IOException{
		ByteBuffer[]bbssp= split(bb);
		for (int i = 0; i < bbssp.length; i++) {
			writableChannel.write(bbssp[i]);
		}
	}

	public ByteBuffer[] split(ByteBuffer bb) {
		//StringBuilder sbd=new StringBuilder("Split:");
		int splitSizex=splitSize;
		int lenth=bb.limit();
		int countofpiece=(lenth-1)/splitSizex+1;
		int remain=lenth%splitSizex;
		ByteBuffer[]pieces=new ByteBuffer[countofpiece];
		for (int i = 0; i < pieces.length; i++) {
			pieces[i]=NetworkPacket.bufferAllocator.allocate(splitSizex+6);
		}
		int sern=series.getAndIncrement();
		for (int i = 0; i < pieces.length; i++) {
			pieces[i].putInt(sern);
			pieces[i].put((byte) countofpiece);
			pieces[i].put((byte) i);
			int bbl=bb.limit();
			bb.limit(Math.min(bb.remaining(), pieces[i].remaining())+bb.position());
			pieces[i].put(bb);
			bb.limit(bbl);
			//sbd.append(pieces[i].position()+" ");
			pieces[i].flip();
		}
		//System.out.println(sbd);
		return pieces;
	}

}
