package vs;

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

/**
 * client for the log service
 *
 * @author Sandro Leuchter
 *
 */
public class ProducerNode {
	private Connection connection;
	private Session session;
	private MessageProducer producer;

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

	/**
	 * creates TextMessage for JMS provider sets String property "Priority" to value
	 * of parameter priority and sends message to Destination of producer, which is
	 * configured in Conf.QUEUE
	 *
	 * @param text     payload of message
	 * @param priority value of String property "Priority"
	 * @throws JMSException JMS exceptions
	 */
	public void sendMessage(String text, String priority) throws JMSException {
		TextMessage message = this.session.createTextMessage();
		message.setText(text);
		message.setStringProperty("Priority", priority);
		this.producer.send(message);
	}

	/**
	 * main routine and starting point of program
	 *
	 * @param args[0] time to wait in ms
	 * @param args[1] of message ("high" or anything else)
	 */
	public static void main(String[] args) {
		String text = args[0];
		String priority = args[1];
		ProducerNode node = null;
		try {
			node = new ProducerNode();
			node.sendMessage(text, priority);
		} catch (NamingException | JMSException e) {
			System.err.println(e);
		} finally {
			try {
				if ((node != null) && (node.producer != null)) {
					node.producer.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);
			}
		}
	}
}
