package com.eactive.eai.flowcontrol.jeus;

import com.eactive.eai.common.util.Logger;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import javax.jms.Connection;
import javax.jms.QueueConnectionFactory;
import javax.jms.Session;
import javax.naming.InitialContext;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class QueueConsumerService  implements InitializingBean, DisposableBean {
	private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	private String uri;
	private String queue;
	private int maxThread; 
	
	Connection connection = null;
	Session[] sessions = null;
	DefaultQueueConsumer[] consumers = null;
	
	public final static String JNDI_FACTORY = "";
	
	ExecutorService es = null; 
			
	public String getUri() {
		return uri;
	}

	public void setUri(String uri) {
		this.uri = uri;
	}

	public String getQueue() {
		return queue;
	}

	public void setQueue(String queue) {
		this.queue = queue;
	}

	public int getMaxThread() {
		return maxThread;
	}

	public void setMaxThread(int maxThread) {
		this.maxThread = maxThread;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		startConsumer();	
	}
	
	@Override
	public void destroy() throws Exception {
		stopConsumer();
	}
	
	public void startConsumer() {
		try {
			InitialContext ctx = new InitialContext();
			QueueConnectionFactory connectionFactory = (QueueConnectionFactory) ctx.lookup(uri);
			es = Executors.newFixedThreadPool(maxThread);

	        connection = connectionFactory.createConnection();
            connection.start();

            consumers = new DefaultQueueConsumer[maxThread];
            
	        for(int i=0; i<maxThread; i++) {
	        	DefaultQueueConsumer consumer = new DefaultQueueConsumer("JEUSJMS-" +i, connection, queue);
	        	es.submit(consumer);
	        	consumers[i] = consumer;
	        }
	        logger.info("Start JEUS JMS QueueListener  [ uri=" + uri + 
	        		", queue="+queue + ", maxthread=" + maxThread+"] and wait for listening");
		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	
	public void stopConsumer() {
		
		for(int i=0; i<maxThread; i++) {
			try {
				consumers[i].stop();
			} catch (Exception e) {
				logger.warn(e.getMessage());
			}
		}
		
		if(es != null) {
			es.shutdown();
		}
		es = null;
		
	}
	
}
