package com.eactive.eai.common.routing;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.jms.Connection;
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import com.eactive.eai.common.util.Logger;

public class TimerEventListenerConsumerService  implements InitializingBean, DisposableBean {
	private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	// uri = "vm://localhost?broker.persistent=false&broker.useJmx=false"
	// uri = "tcp://localhost:61617""
	private String uri;
	private String queue;
	private int maxThread; 
	
	Connection connection = null;
	Session[] sessions = null;
	TimerEventListener[] consumers = null;
	
	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 {
			ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(uri);
			connectionFactory.setTrustAllPackages(true);

			es = Executors.newFixedThreadPool(maxThread);

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

            consumers = new TimerEventListener[maxThread];
            
	        for(int i=0; i<maxThread; i++) {
	        	TimerEventListener consumer = new TimerEventListener("AMQ-" +i, connection, queue);
	        	es.submit(consumer);
	        	consumers[i] = consumer;
	        }
	        logger.info("Start ActiveMQ QueueListener  [ uri=" + uri + 
	        		", queue="+queue + ", maxthread=" + maxThread+"] and wait for listening");
		}
		catch(Exception ex) {
        	logger.error(ex.getMessage(), ex);
		}
	}
	
	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;
		
	}
	
	public static void main(String[] argv) throws Exception {
		TimerEventListenerConsumerService service = new TimerEventListenerConsumerService();
		service.setUri("vm://localhost?broker.persistent=false&broker.useJmx=false");
		service.setQueue("TESTQ1");
		service.setMaxThread(10);
		service.startConsumer();
		
		Thread.sleep(2 * 1000);
		
		service.stopConsumer();
		
		Thread.sleep(2 * 1000);
	}
}
