package vs;

import jakarta.jms.Connection;
import jakarta.jms.ConnectionFactory;
import jakarta.jms.Destination;
import jakarta.jms.JMSException;
import jakarta.jms.Message;
import jakarta.jms.MessageConsumer;
import jakarta.jms.Session;
import jakarta.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * synchronous provider for the log service
 *
 * @author Sandro Leuchter
 *
 */

public class ConsumerPullNode {
	private Connection connection;
	private Session session;
	private MessageConsumer consumer;

	/**
	 * constructor, establishes and starts connection to JMS provider specified in
	 * JNDI (via jndi.properties), afterwards consumer is ready
	 *
	 * @throws NamingException JNDI exceptions
	 * @throws JMSException    JMS exceptions
	 */
	public ConsumerPullNode() throws NamingException, JMSException {
		Context ctx = new InitialContext();
		ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");
		Destination queue = (Destination) ctx.lookup(Conf.QUEUE);
		this.connection = factory.createConnection();
		this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		this.consumer = this.session.createConsumer(queue);
		this.connection.start();
	}

	/**
	 * synchronously receives the TextMessages in an infinite loop and prints
	 * payload text to StdOut
	 *
	 * @param timeout timeout in ms
	 * @see jakarta.jms.TextMessage
	 * @throws JMSException JMS exceptions
	 */
	public void receiveAndPrintMessages(long timeout) throws JMSException {
		Message message;
		while ((message = this.consumer.receive(timeout)) != null) {
			if (message instanceof TextMessage) {
				TextMessage textMessage = (TextMessage) message;
				String messageText = textMessage.getText();
				System.out.println(messageText);
			}
		}
	}

	/**
	 * main routine and starting point of program
	 *
	 * @param args[0] time to wait in ms
	 */
	public static void main(String[] args) {
		long timeout = Long.parseLong(args[0]);
		ConsumerPullNode node = null;
		try {
			node = new ConsumerPullNode();
			node.receiveAndPrintMessages(timeout);
		} catch (NamingException | JMSException e) {
			System.err.println(e);
		} finally {
			try {
				if ((node != null) && (node.consumer != null)) {
					node.consumer.close();
				}
				if ((node != null) && (node.session != null)) {
					node.session.close();
				}
				if ((node != null) && (node.connection != null)) {
					node.connection.close();
				}
			} catch (JMSException e) {
				System.err.println(e);
			}
		}
	}
}
