package com.eactive.eai.common.activemq;

import java.util.Properties;

import javax.jms.Connection;
import javax.jms.JMSException;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.pool.PooledConnectionFactory;

import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.routing.RouteKeys;

public class AmqPooledConnectionFactory {
	public static String CONNECTION_URI = "vm://localhost?broker.persistent=false&broker.useJmx=true&jms.useAsyncSend=true&jms.prefetchPolicy.all=0";

	private static final AmqPooledConnectionFactory instance = new AmqPooledConnectionFactory();

	private PooledConnectionFactory pooledConnectionFactory;

	public static AmqPooledConnectionFactory getInstance() {
		return instance;
	}

	private AmqPooledConnectionFactory() {
		createNewFactory();
	}

	public Connection getConnection() throws JMSException {
		return pooledConnectionFactory.createConnection();
	}

	private void createNewFactory() {
		ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(CONNECTION_URI);
		connectionFactory.setTrustAllPackages(true);

		// Create a PooledConnectionFactory and set some configuration options
		pooledConnectionFactory = new PooledConnectionFactory();
		pooledConnectionFactory.setConnectionFactory(connectionFactory);

		setConnectionProperties();

		pooledConnectionFactory.start();
	}

	private PooledConnectionFactory setConnectionProperties() {
		Properties props = PropManager.getInstance().getProperties(RouteKeys.GROUP_NAME);
		int maxConnection = Integer
				.parseInt(props.getProperty(RouteKeys.ROUTING_QUEUE_CONNECTION_FACTORY_MAXCONNECTION, "5"));

		long expiryTimeout = Long
				.parseLong(props.getProperty(RouteKeys.ROUTING_QUEUE_CONNECTION_FACTORY_EXPIRYTIMEOUT, "0"));

		int idleTimeout = Integer
				.parseInt(props.getProperty(RouteKeys.ROUTING_QUEUE_CONNECTION_FACTORY_IDLETIMEOUT, "30000"));

		pooledConnectionFactory.setMaxConnections(maxConnection);
		pooledConnectionFactory.setIdleTimeout(idleTimeout);
		pooledConnectionFactory.setExpiryTimeout(expiryTimeout);

		return pooledConnectionFactory;
	}

	public PooledConnectionFactory reload() {
		return setConnectionProperties();
	}

}
