package var.mom.jms.reverse;

import org.w3c.dom.Text;

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

public class Reverser implements MessageListener {
    private Connection connection;
    private Session session;
    private MessageConsumer consumer;

    public Reverser() 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);
        consumer = session.createConsumer(queue);
        consumer.setMessageListener(this);

        connection.start();
    }

    @Override
    public void onMessage(Message message) {
        try {
            if (message instanceof TextMessage) {
                TextMessage textMessage = (TextMessage) message;

                System.out.println("Received: " + textMessage.getText());

                    StringBuilder sb = new StringBuilder();
                    sb.append(textMessage.getText());
                    sb.reverse();

                    Destination replyQueue = message.getJMSReplyTo();
                    MessageProducer producer = session.createProducer(replyQueue);

                    TextMessage replyMessage = session.createTextMessage();
                    replyMessage.setText(sb.toString());
                    replyMessage.setStringProperty("Priority", message.getStringProperty("Priority"));

                    producer.send(replyMessage);
            }
        } catch (JMSException e) {
            System.err.println(e);
        }
    }

    static void main(String[] args) {
        Reverser node = null;

        try {
            node = new Reverser();
            Thread.sleep(1000000);
        }
        catch (NamingException | JMSException | InterruptedException 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) {
                    throw new RuntimeException(e);
                }
        }
    }
}
