package com.eactive.eai.common.activemq;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

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

public class AmqTopicProducer {
	
	Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	
	Connection connection = null;
	Session session = null;
	MessageProducer producer = null;
	String connectionUrl = null;
	String topicName = null;
	String correlationID = null;
	
	public AmqTopicProducer(String connectionUrl, String topicName, String correlationID) {
		this.connectionUrl = connectionUrl;
		this.topicName = topicName;
		this.correlationID = correlationID;
	}
	
	@SuppressWarnings("rawtypes")
	public void sendMessage(Serializable object, Properties prop, long ttl) throws JMSException {
		try {
	        // Create a Connection
	        connection = AmqPooledConnectionFactory.getInstance().getConnection();
	
	        // Create a Session
	        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
	
	        // Create the destination (Topic or Queue)
	        Destination destination = session.createTopic(topicName);
	        producer = session.createProducer(destination);
	        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
			ObjectMessage message = session.createObjectMessage(object);
			
			 if(ttl > 0) {
            	producer.setTimeToLive(ttl);
            }
		 
			if (correlationID != null) {
				message.setJMSCorrelationID(correlationID);
			}
			
			if (prop != null) {
				Iterator it = prop.keySet().iterator();
				while (it.hasNext()) {
					String key = (String) it.next();
					String value = prop.getProperty(key);
					message.setStringProperty(key, value);
				}
			}
            
			producer.send(message);
		}
		catch(JMSException ex) {
			logger.error("Send Error = " + ex.getMessage(), ex);
			throw ex;
		}
		finally {
			if (producer != null) {
				try {
					producer.close();
				} catch (Exception e) {
					// ignored
				}
			}
			if (session != null)
				try {
					session.close();
				} catch (JMSException e) {
					// ignored
				}
			if (connection != null)
				try {
					connection.close();
				} catch (JMSException e) {
					// ignored
				}
		}
	}	
}
