package com.eactive.eai.common.routing.jms;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Queue;
import javax.jms.Session;


import com.eactive.eai.common.dao.Keys;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.ServiceLocator;

public abstract class AbstractQueueConsumer  implements Runnable, ExceptionListener {
	
	private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	
	
	Connection connection = null;
	Session session = null;
	MessageConsumer consumer = null;
	String name = null;
	String queue = null;
	boolean run = true;
	
	public AbstractQueueConsumer(String name, Connection con, String queue) {
		this.connection = con;
		 try {
			 
			String serverName = System.getProperty(Keys.SERVER_KEY);
		 	if("bapSvr11".equals(serverName)) {
		 		queue = queue.replace("21", "11");
			}else {
				queue = queue.replace("11", "21");
			}
				
			 this.name = name;
			 this.queue = queue;
			connection.start();
			connection.setExceptionListener(this);

	        // Create a Session
	        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

			ServiceLocator locator = ServiceLocator.getInstance();
	        
			Destination destination = (Queue)locator.getQueue(queue);
			
	         // Create the destination (Topic or Queue)
//	        Destination destination = session.createQueue(queue);
	        consumer = session.createConsumer(destination); 
	        
//	        QueueSession session = ((QueueConnection) connection).createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
//	        QueueReceiver receive = session.createReceiver(session.createQueue(queue));
//            receive.setMessageListener(new JMSQueueReceiver());
		} catch (JMSException e) {
			e.printStackTrace();
		} catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		if ( consumer == null ) {
			stop();
		}
		while (run) {
			excute();
		}
	}
	public abstract void excute();
	
	public void stop() {
		run = false;
        if(consumer != null)
				try {
					consumer.close();
				} catch (JMSException e) { }
    	if(session != null)
				try {
					session.close();
				} catch (JMSException e) { }
    	if(connection != null)
				try {
					connection.close();
				} catch (JMSException e) { }
	}
	
	@Override
	public void onException(JMSException arg0) {
		 logger.error("JMS Exception occured.  Shutting down client.");
		 stop();
	}
}
