package com.tipcj.demos;

import java.nio.ByteBuffer;

import com.tipcj.*;

public class Hello_Java_Api_Client {
	public static final int SERVER_TYPE  = 18888;
	public static final int SERVER_INST  = 17;
	public static final int BUF_SIZE = 40;

	public static void main(String[] args) {
		TipcConn tipcConn = null;
		TipcAddr server = new TipcAddr(SERVER_TYPE, SERVER_INST, 0);
		byte[] inbuf = new byte[BUF_SIZE];
		byte[] outbuf = new String("Hello World!!!").getBytes();
		boolean up = false;
		ByteBuffer bytebuffer = ByteBuffer.allocateDirect(BUF_SIZE);

		System.out.println("****** TIPC hello world client started ******\n");

		up = TipcSrvConn.SrvWait(server, 10000);
		if (!up) {
			System.out.println("Client: server {" + SERVER_TYPE + "," + SERVER_INST + "} not published within 10 [s]");
			return;
		}

		tipcConn = new TipcConn(SocketType.SOCK_RDM);
		if (tipcConn.Sendto(outbuf, server) < 0) {
			System.out.println("Client: failed to send");
			tipcConn.Close();
			return;
		}

		System.out.println("Client: sent message: " + new String(outbuf));

		int ret = tipcConn.Recv(bytebuffer, bytebuffer.capacity(), false);
		if (ret <= 0 ) {
			System.out.println("Client: unexpected response");
			tipcConn.Close();
			return;
		}

		bytebuffer.get(inbuf, 0, ret);
		System.out.println("Client: received response: " + new String(inbuf));

		/**
		 * Topology tracking
		 */
		/**
		TipcSrvConn srvTrack = new TipcSrvConn(0, ServiceType.TIPC_LINK_STATE);
		TipcAddr srvAddr = new TipcAddr();
		TipcAddr idAddr = new TipcAddr();
		Integer upEvt = new Integer(0);
		Integer expire = new Integer(0);

		while (srvTrack.GetEvt(srvAddr, idAddr, upEvt, expire) >= 0) {
			System.out.println(srvAddr + "-" + idAddr + "-" + upEvt.toString() + "-" + expire.toString());
			try {
				//sleep 1 seconds
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		*/
		System.out.println("****** TIPC hello client finished ******");
		tipcConn.Close();
	}
}
