package var.mom.jms.reverse;

import var.mom.jms.log.ProducerNode;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class Requester {
    private Connection connection;
    private Session session;
    private MessageProducer producer;
    private Queue replyQueue;
    private MessageConsumer consumer;

    public Requester() throws NamingException, JMSException {
        Context ctx = new InitialContext();
        ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");

        connection = factory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        Destination queue = (Destination) ctx.lookup(Conf.QUEUE);
        producer = session.createProducer(queue);

        replyQueue = session.createTemporaryQueue();
        consumer = session.createConsumer(replyQueue);

        connection.start();
    }

    public void sendMessage(String text, String priority) throws JMSException {
        TextMessage message = session.createTextMessage();
        message.setText(text);
        message.setStringProperty("Priority", priority);

        message.setJMSReplyTo(replyQueue);
        producer.send(message);
    }
    public void receiveMessage() throws JMSException {
        Message message = consumer.receive();
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            System.out.println("Received: " + textMessage.getText());
        }
    }

    static void main(String[] args) {
        String text = "Hiiiiiiillll";
        String priority = "High";
        Requester node = null;

        try {
            node = new Requester();
            node.sendMessage(text, priority);
            node.receiveMessage();

        }
        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);
            }
        }
    }
}
