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.MessageListener;
import jakarta.jms.Session;
import jakarta.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * asynchronous provider for the log service, flitering only messages with
 * String property "Priority"=="high"
 *
 * @author Sandro Leuchter
 *
 */

public class ConsumerFilteredNode implements MessageListener {
	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 filtering only
	 * messages with String property "Priority" set to "high"
	 *
	 * @throws NamingException JNDI exceptions
	 * @throws JMSException    JMS exceptions
	 */
	public ConsumerFilteredNode() 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, "Priority='high'");
		this.consumer.setMessageListener(this);
		this.connection.start();
	}

	/**
	 * asynchronous message consumption
	 *
	 * @see jakarta.jms.MessageListener
	 */
	@Override
	public void onMessage(Message message) {
		try {
			if (message instanceof TextMessage) {
				TextMessage textMessage = (TextMessage) message;
				String messageText = textMessage.getText();
				String priority = textMessage.getStringProperty("Priority");
				System.out.println(messageText + " [Priority=" + priority + "]");
			}
		} catch (JMSException e) {
			System.err.println(e);
		}
	}

	/**
	 * main routine and starting point of program
	 *
	 * @param args[0] time to wait in ms
	 */
	public static void main(String[] args) {
		long wait = Long.parseLong(args[0]);
		ConsumerFilteredNode node = null;
		try {
			node = new ConsumerFilteredNode();
			Thread.sleep(wait);
		} catch (InterruptedException | 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);
			}
		}
	}

}
