package at.ac.tuwien.sbc.valesriegler.driver.jms;

import at.ac.tuwien.sbc.valesriegler.common.HasId;
import at.ac.tuwien.sbc.valesriegler.driver.jms.messageListeners.CookedDeliveryOrders;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;

/**
 * JMSDriver registers all the Listeners.
 * 
 * @author jan
 * 
 */
public class JMSDriver implements HasId {
	private static final Logger log = LoggerFactory.getLogger(JMSDriver.class);
	private final String CONNECTSTRING;
	public String getCONNECTSTRING() {
		return CONNECTSTRING;
	}

	final private int id;

	public JMSDriver(String jmsURL, int id) {
		CONNECTSTRING = jmsURL;
		this.id = id;
		log.info("I AM A JMSDriver WITH ID {}", this.id);

		try {
			// Connecting to the Broker and to the output queue
			ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(CONNECTSTRING);
			Connection connection = connectionFactory.createConnection();
			connection.start();

			Session sessCookedDeliveryOrders = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
			MessageConsumer consCookedDeliveryOrders = sessCookedDeliveryOrders.createConsumer(sessCookedDeliveryOrders
					.createQueue("CookedDeliveryOrders"));
			consCookedDeliveryOrders.setMessageListener(new CookedDeliveryOrders(this));
		} catch (JMSException e) {
			log.error("EXCEPTION!", e);
		}
	}

	@Override
	public int getId() {
		return id;
	}
}
