/*******************************************************************************
 * This file is part of GECAMed.
 * 
 * GECAMed is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License (L-GPL) as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GECAMed is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License (L-GPL)
 * along with GECAMed.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * GECAMed is Copyrighted by the Centre de Recherche Public Henri Tudor (http://www.tudor.lu)
 * (c) CRP Henri Tudor, Luxembourg, 2008
 *******************************************************************************/
/*
 * Author: Johannes Hermen Tudor/Santec
 * Mail: johannes.hermen@tudor.lu
 * Created: Mar 10, 2005
 *
 */
package lu.tudor.santec.gecamed.core.gui.utils;

import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.MessageListener;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;


/**
 * this class handles the message-recieving for GeCam.
 * Messages that can be send by a JMS-Sender are recieved and handled by this class
 *
 * @author Johannes Hermen johannes.hermen@tudor.lu Tudor/Santec
 *
 */
public class GeneralGECAMedTextMessageReciever
{
    //~ Static fields/initializers =============================================

	/**
	 * static logger for this class
	 */
	private static Logger logger = Logger
			.getLogger(GeneralGECAMedTextMessageReciever.class.getName());
	
    /**
     * the name of the Topic to descripe to. this MessageTopic has to exist in the
     * JBoss configuration
     */
    public static final String TOPIC_NAME = "topic/GeCam/textTopic";

    public static final String PRESCRIPTION_LIST_UPDATE_TOPIC = "topic/GeCam/prescriptionListUpdaterTopic";

    public static final String LOG_TOPIC ="topic/GECAMed/gecamedLog";

    //~ Instance fields ========================================================


    private Topic topic = null;

    private TopicConnection conn = null;
    private TopicSession session = null;

//	private Topic logTopic;

	private String topicName;

	private MessageListener listener;

	private TopicSubscriber recv;

    //~ Constructors ===========================================================
    /**
     * creates a new MessageReciever for JMS Message handling
     *
     * @param mainFrame a reference to the mainFrame of the Program to obtain all child-objects from
     */
    public GeneralGECAMedTextMessageReciever(String topicName, MessageListener listener)
    {
        super();
        this.topicName = topicName;
        this.listener = listener;
        this.recieve();
    }

    //~ Methods ================================================================

    public void recieve()
    {
        try {
            // Setup the PubSub connection, session
            initJMS();
            // Set the async listener
            /* ----------------------------------------------------- */
            recv = session.createSubscriber(topic);
            recv.setMessageListener(listener);
            /* ----------------------------------------------------- */
        } catch (Exception e) {
            logger.log(Level.WARN, "recieving jms failed", e);
        }
    }

    /**
     * stops the JMS thread by setting the counter to zero
     */
    public static void stopRecieving()
    {
        //        counter.release();
        //        GECAMedTextMessageReciever.counter.acquire();
        //        conn.stop();
        //        session.close();
        //        conn.close();
    }

    /**
     * subscribes to the specified channel and opens a JMS connection
     *
     * @throws JMSException
     * @throws NamingException
     */
    private void initJMS() throws JMSException, NamingException
    {
        InitialContext iniCtx = new InitialContext();
        Object tmp = iniCtx.lookup("ConnectionFactory");
        TopicConnectionFactory tcf = (TopicConnectionFactory) tmp;
        conn = tcf.createTopicConnection();
        /* ----------------------------------------------------- */
        // GeCam textMessage Topic
        topic = (Topic) iniCtx.lookup(this.topicName);
        /* ----------------------------------------------------- */
        session = conn.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
        conn.start();
        conn.setExceptionListener(new ExceptionListener() {
			public void onException(JMSException e) {
				try {
					logger.warn("JMS Topic Connection lost, closing Connection.", e);
					if (recv != null) 	recv.close();
					if (session != null)session.close();
					if (conn != null) 		conn.close();
				} catch (Throwable ee) {
					logger.error("Error Closing JMS Topic Connection", ee);
				}
				
			}
		});
    }
}

