package org.tp23.yeti;

import org.mpilone.yeti.Frame;
import org.mpilone.yeti.FrameBuilder;
import org.mpilone.yeti.client.StompClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

import static java.lang.Thread.sleep;
import static java.util.concurrent.TimeUnit.*;

/**
 * xtomp client using Yeti https://github.com/mpilone/hazelcastmq/blob/master/yeti/README.md
 *
 * @author teknopaul
 */
public class XtompYetiClient {

	private static final Logger LOG = LoggerFactory.getLogger(XtompYetiClient.class);

	private static final String HOST = "localhost";

	private static final int PORT = 61613;

	private static final String DESTINATION = "memtop-a";

	public static void main(String[] args) throws InterruptedException {

		StompClient.QueuingFrameListener msgListener = new StompClient.QueuingFrameListener();

		StompClient client = new StompClient(true, HOST, PORT);

		client.connect();

		// N.B. subscription ID needs to be a number as a String "1"
		client.subscribe(FrameBuilder.subscribe(DESTINATION, "1").build(), msgListener);

		new Thread( () -> {
			try {
				// Wait for the messages to arrive. We should get two of them.
				Frame msg1 = msgListener.poll(2, SECONDS);
				LOG.info("Got message 1: " + msg1.getBodyAsString());

				Frame msg2 = msgListener.poll(160100L, MILLISECONDS);
				LOG.info("Got message 2: " + msg2.getBodyAsString());

				// polite disconnect
				client.unsubscribe(FrameBuilder.unsubscribe("1").build());
				client.disconnect();

			}
			catch (InterruptedException ex) {
				LOG.error("Never got no message");
				System.exit(1);
			}
		}).start();

		sleep(100l);

		client.send(FrameBuilder.send("memtop-a", "\nHello\nWorld!\n").build());

		// test heart-beating by waiting for longer than default timeout.
		sleep(160000L);

		client.send(FrameBuilder.send("memtop-a", "message 2").build());

	}

}