package hh.dejsem.net;

import java.nio.ByteBuffer;

import hh.dejsem.K;
import hh.lib.D;

/**
 * network data sent and received
 */
public class NetData {
	D d;
	public ByteBuffer buf;
	public byte[] nb;
	public String data;
	int n;
	/* ----------------------------------------------------------*/

	public NetData(D d, byte[] b) {
		this.d = d.klon("DATA");
		load(b);
	}

	public NetData(D d, String s) {
		this.d = d.klon(this);
		load(s);
	}

	public NetData(D d) { this(d, K.buffSize); }

	public NetData(D d, int size) {
		this.d = d.klon(this);
		buf = ByteBuffer.allocate(size);
		nb = new byte[size];
		data = "";
	}

	void load(byte[] b) {
		if(n < 0) n = 0;
		buf = ByteBuffer.wrap(b, 0, n);
		if(d.ll(5)) d.l("loaded from byte data[" + n + "]: buf=" + D.bufStat(buf));
	}

	void load(String s) {
		if(d.ll(5)) d.l("loading data from string[" + s.length() + "]...");
		buf = ByteBuffer.wrap(s.getBytes());
		nb = s.getBytes();
	}

	void append() {
		if(d.ll(5)) d.l("appending buffer " + D.bufStat(buf) + " + " + n);
		if(buf.remaining() < n) inflate();
		buf.put(nb, 0, n);
	}

	void inflate() {
		if(d.ll(4)) d.l("doubling buffer " + D.bufStat(buf));
		ByteBuffer b = ByteBuffer.allocate(2 * buf.capacity());
		buf.rewind();
		b.put(buf);
		buf = b;
	}

	public void unloadToString() {
		if(d.ll(5)) d.l("unloading buffer[" + D.bufStat(buf) + "]...");
		byte[] b = new byte[buf.position()];
		buf.flip();
		buf.get(b);
		data = new String(b);
	}

	public void unloadToByte() {
		if(d.ll(5)) d.l("unloading buffer[" + D.bufStat(buf) + "]...");
		nb = new byte[buf.position()];
		buf.flip();
		buf.get(nb);
	}
}
