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

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

import org.apache.activemq.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import at.ac.tuwien.sbc.valesriegler.common.HasId;
import at.ac.tuwien.sbc.valesriegler.cook.jms.messageListeners.DeliveryOrdersToCook;
import at.ac.tuwien.sbc.valesriegler.cook.jms.messageListeners.OrdersToCook;

/**
 * JMSCook registers 2 Listeners. We do this to prevent a starvation of groups inside the pizzeria. But on the other
 * hand we dont require all pizzas inside the pizzeria to be cooked before we start cooking DeliveryOrders.
 * 
 * @author jan
 * 
 */
public class JMSCook implements HasId {
	private static final Logger log = LoggerFactory.getLogger(JMSCook.class);
	private final String CONNECTSTRING;
	final private int id;

	public JMSCook(String jmsURL, int id) {
		CONNECTSTRING = jmsURL;
		this.id = id;
		log.info("I AM A JMSCook 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 sessOrdersToCook = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
			MessageConsumer consOrdersToCook = sessOrdersToCook.createConsumer(sessOrdersToCook.createQueue("OrdersToCook"));
			consOrdersToCook.setMessageListener(new OrdersToCook(this));

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

	public String getCONNECTSTRING() {
		return CONNECTSTRING;
	}

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