package com.eactive.eai.control;

import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;

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


public class JMSQueueSender {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	private QueueConnectionFactory factory; 
	private QueueConnection con = null;
	private QueueSession ses = null;
	private QueueSender qsender;
    private Queue queue = null;
    private TextMessage msg;
    private ObjectMessage objmsg;
    
    private String jms_connectionfactory;
    private String queue_name;
    
    public void send(String queueConnectionFactory, String queueName, String message, String id) throws JMSException {
        init(queueConnectionFactory, queueName);
        if(ses !=null) msg = ses.createTextMessage();
        if(id!=null) msg.setJMSCorrelationID(id);
        msg.setText(message);
        qsender.send(msg);
        closeQueueConnection();
    }
    
    public void sendObject(String queueConnectionFactory, String queueName, java.io.Serializable message, String id) throws JMSException {

        init(queueConnectionFactory, queueName);
        if(ses !=null) objmsg = ses.createObjectMessage();
        if(id!=null) objmsg.setJMSCorrelationID(id);
        objmsg.setObject(message);
        qsender.send(objmsg);
        closeQueueConnection();
    }
    
    public void init(String queueConnectionFactory, String queueName) {
        jms_connectionfactory = queueConnectionFactory;
        queue_name = queueName;
        startQueueConnection();
    }
    
    
    public void close() {
       closeQueueConnection();    
    }
    
    private void startQueueConnection() {
        try {
        	JmsServiceLocator locator = JmsServiceLocator.getInstance();            
            
			factory = locator.getQueueConnectionFactory(jms_connectionfactory);
			if(factory == null) throw new Exception("factory not found - " + jms_connectionfactory);
			con = factory.createQueueConnection();
			if(con == null) throw new Exception("createQueueConnection return null");
			ses = con.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
			if(ses == null) throw new Exception("createQueueSession return null");
            queue = (Queue)locator.getQueue(queue_name);
			qsender = ses.createSender(queue);
        	con.start();
		} catch (Throwable e) {
			closeQueueConnection();
		}
    }
    private void closeQueueConnection() {
		if (ses != null) try { ses.close(); ses = null; } catch (Throwable e) {
			logger.debug(e.toString());
		}
		if (con != null) try { con.stop(); } catch (Throwable e) {
			logger.debug(e.toString());
		}
		if (con != null) try { con.close(); con = null; } catch (Throwable e) {
			logger.debug(e.toString());
		}
    }
}
