package com.eactive.eai.flowcontrol.websphere;

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 = "com.ibm.websphere.naming.WsninittialContextFactory";
	
	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("WebsphereJMS-" +i, connection, queue);
	        	es.submit(consumer);
	        	consumers[i] = consumer;
	        }
	        logger.info("Start Websphere JMS QueueListener  [ uri=" + uri + 
	        		", queue="+queue + ", maxthread=" + maxThread+"] and wait for listening");
		}
		catch(Exception ex) {
			logger.error("startConsumer error", 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 args[]) throws Exception {
//	   test();
//}

// private static void test() throws Exception {
//		QueueConsumerService service = new QueueConsumerService();
//		service.setUri("xxx");
//		service.setQueue("TESTQ1");
//		service.setMaxThread(10);
//		service.startConsumer();
//		
//		Thread.sleep(2 * 1000);
//		
//		service.stopConsumer();
//		
//		Thread.sleep(2 * 1000);
//	}
}
