package hh.dejsem.net;

import java.nio.ByteBuffer;

import hh.lib.D;

/**
 * helpers for some specific operations on IO channel (java.nio)
 */
public class NetChOps {
	static String tag = "NetChOps";

	public static long getNum(D d, GetPut io) throws Exception {
		ByteBuffer buf = ByteBuffer.allocate(12);
		while(buf.remaining() > 0) if(!io.get(buf)) break;
		if(buf.remaining() > 0) return -2;
		if(d.ll(5)) d.log(tag + ".getNum", "read ByteBuffer=" +  D.bufStat(buf));
		buf.flip();
		byte[] b = new byte[12];
		buf.get(b);
		if(d.ll(5)) d.log(tag + ".getNum", String.format("num read=%d", Long.valueOf(new String(b))));
		return Long.valueOf(new String(b));
	}

	public static void putNum(D d, long n, GetPut io) throws Exception {
		if(d.ll(5)) d.log(tag + ".putNum", String.format("num to put=%012d", n));
		io.put(ByteBuffer.wrap(String.format("%012d", n).getBytes()));
	}

	public static String getStr(D d, GetPut io) throws Exception {
		int len = (int)getNum(d, io);
		if(d.ll(5)) d.log(tag + ".getStr", "length of string to get=" + len);
		if(len == -2) return null;		// EOD in input data
		if(len == 0) return "";
		ByteBuffer buf = ByteBuffer.allocate(len);
		while(buf.remaining() > 0) { if(!io.get(buf)) break; }
		buf.flip();
		byte[] b = new byte[len];
		buf.get(b);
		String got = new String(b, 0, len);
		if(d.ll(5)) d.log(tag + ".getStr", "string got=" + got);
		return got;
	}

	public static void putStr(D d, String fn, GetPut io) throws Exception {
		if(d.ll(5)) d.log(tag + ".putStr", "string to put=" + fn);
		byte[] b = fn.getBytes();
		putNum(d, b.length, io);
		io.put(ByteBuffer.wrap(fn.getBytes()));
	}
}
