package vs;

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

/**
 * replier node for the echo service
 *
 * @author Sandro Leuchter
 *
 */
public class EchoReplierNode 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
	 *
	 * @throws NamingException JNDI exceptions
	 * @throws JMSException    JMS exceptions
	 */
	public EchoReplierNode() throws NamingException, JMSException {
		Context ctx = new InitialContext();
		ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");
		Queue queue = (Queue) ctx.lookup(Conf.QUEUE);
		this.connection = factory.createConnection();
		this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		this.consumer = this.session.createConsumer(queue);
		this.consumer.setMessageListener(this);
		this.connection.start();
	}

	/**
	 * asynchronous message consumption
	 *
	 * @see jakarta.jms.MessageListener
	 */
	@Override
	public void onMessage(Message request) {
		try {
			if (request instanceof TextMessage) {
				TextMessage requestText = (TextMessage) request;
				System.out.println("empfangen: " + requestText.getText());
				MessageProducer replyProducer = this.session.createProducer(request.getJMSReplyTo());
				TextMessage reply = this.session.createTextMessage();
				reply.setText("echo: " + requestText.getText());
				Thread.sleep(5000);
				replyProducer.send(reply);
				replyProducer.close();
			}
		} catch (JMSException | InterruptedException e) {
			System.err.println(e);
		}

	}

	/**
	 * main routine and starting point of program
	 *
	 * @param args not used
	 */
	public static void main(String[] args) {
		EchoReplierNode node = null;
		try {
			node = new EchoReplierNode();
			while (true) {
				Thread.sleep(1000);
			}
		} 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);
			}
		}
	}
}
