/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library 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 along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.jms;

import java.io.Serializable;

import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueBrowser;
import javax.jms.Session;
import javax.jms.StreamMessage;
import javax.jms.TemporaryQueue;
import javax.jms.TemporaryTopic;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicSubscriber;
import javax.jms.XAConnection;
import javax.jms.XASession;
import javax.transaction.RollbackException;
import javax.transaction.Synchronization;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.xa.XAResource;

import org.ow2.jonas.tm.TransactionManager;


import org.objectweb.util.monolog.api.BasicLevel;


/**
 * JSession
 * @author Laurent Chauvirey, Frederic Maistre, Nicolas Tachker
 * Contributor(s):
 * Philippe Durieux
 * Philippe Coq
 */

public class JSession implements Session, Synchronization {

    protected XAResource xares = null;	// The underlaying XAResource
    protected boolean txover = true;
    protected Transaction currtx = null;
    protected boolean closed = false;
    protected JConnection jconn;
    protected static TransactionManager tm = null;

    protected XAConnection xac;
    protected Session sess = null;
    protected XASession xasess = null;

    /**
     * Prepares the construction of a JSession.
     * @param jconn
     */
    protected JSession(JConnection jconn) {
        this.jconn = jconn;
        if (tm == null) {
            tm = JmsManagerImpl.getTransactionManager();
        }
    }

    /**
     * Constructor
     */
    public JSession(JConnection jconn, XAConnection xac) {
        this(jconn);
        this.xac = xac;
        TraceJms.logger.log(BasicLevel.DEBUG,"");
    }

    // -----------------------------------------------------------------------
    // Internal Methods
    // -----------------------------------------------------------------------

    /**
     * Get the underlaying XAResource.
     * @return - XAResource
     */
    protected XAResource getXAResource() {
        return xares;
    }

    /**
     * Get the underlaying MOM Session.
     * @return - session
     */
    protected Session getMOMSession() throws JMSException {
        Transaction tx = null;
        try {
            tx = tm.getTransaction();
        } catch (SystemException e) {
            TraceJms.logger.log(BasicLevel.ERROR,"cannot get Transaction");
        }
        if (tx == null) {
            if (sess == null) {
                sess = xac.createSession(false, Session.AUTO_ACKNOWLEDGE);
                jconn.sessionOpen(this);
            }
            return sess;
        } else {
            if (xasess == null) {
                xasess = xac.createXASession();
                if (currtx != null) {
                    TraceJms.logger.log(BasicLevel.ERROR,"mixed transactions");
                }
                currtx = tx;
                xares = xasess.getXAResource();
                try {
                    tx.enlistResource(xares);
                    txover = false;
                } catch (SystemException e) {
                    TraceJms.logger.log(BasicLevel.ERROR,"cannot enlist session:"+e);
                    throw new JMSException(e.toString());
                } catch (RollbackException e) {
                    TraceJms.logger.log(BasicLevel.ERROR,"transaction rolled back");
                    throw new JMSException(e.toString());
                }
            }
            return xasess.getSession();
        }
    }

    protected void MOMSessionClose() {
        try {
            if (xasess != null) {
                xasess.close();
                xasess = null;
            }
            if (sess != null) {
                sess.close();
                sess = null;
                jconn.sessionClose(this);
            }
        } catch (JMSException e) {
            TraceJms.logger.log(BasicLevel.ERROR,"exception:"+e);
        }
    }

    /**
     *
     */
    protected void PhysicalClose() {
        MOMSessionClose();
    }

    // -----------------------------------------------------------------------
    // Session Implementation
    // -----------------------------------------------------------------------

    /**
     *
     */
    public void close() throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        closed = true;
        if (txover) {
            PhysicalClose();
        } else {
            // delist XAResource now, that will lead to an XA-end call
            if (currtx == null) {
                TraceJms.logger.log(BasicLevel.ERROR, "should be in a tx");
            } else {
                try {
                    currtx.delistResource(xares, XAResource.TMSUCCESS);
                } catch (SystemException e) {
                    TraceJms.logger.log(BasicLevel.ERROR, "cannot delist session:"+e);
                    throw new JMSException(e.toString());
                }
            }
        }
    }

    /**
     *
     */
    public void commit() throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        throw new JMSException("JSession: commit Operation Not Allowed");
    }

    /**
     *
     */
    public QueueBrowser createBrowser(Queue queue)
        throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createBrowser(queue);
    }

    /**
     *
     */
    public QueueBrowser createBrowser(Queue queue, java.lang.String messageSelector)
        throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createBrowser(queue, messageSelector);
    }

    /**
     *
     */
    public BytesMessage createBytesMessage() throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createBytesMessage();
    }


    /**
     *
     */
    public MessageConsumer createConsumer(Destination destination)
        throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createConsumer(destination);
    }


    /**
     *
     */
    public MessageConsumer createConsumer(Destination destination,
                                          String messageSelector)
        throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createConsumer(destination, messageSelector);
    }

    /**
     *
     */
    public MessageConsumer createConsumer(Destination destination,
                                          String messageSelector,
                                          boolean NoLocal)
        throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createConsumer(destination, messageSelector,NoLocal );
    }

    /**
     *
     */
    public TopicSubscriber createDurableSubscriber(Topic topic,
                                                   String name)
        throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createDurableSubscriber(topic, name);
    }

    /**
     *
     */
    public TopicSubscriber createDurableSubscriber(Topic topic,
                                                   String name,
                                                   String messageSelector,
                                                   boolean noLocal)
        throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createDurableSubscriber(topic, name, messageSelector, noLocal);
    }

    /**
     *
     */
    public MapMessage createMapMessage() throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createMapMessage();
    }

    /**
     *
     */
    public Message createMessage() throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createMessage();
    }

    /**
     *
     */
    public ObjectMessage createObjectMessage() throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createObjectMessage();
    }

    /**
     *
     */
    public ObjectMessage createObjectMessage(Serializable object) throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createObjectMessage(object);
    }

    /**
     *
     */
    public MessageProducer createProducer(Destination destination)
        throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createProducer(destination);
    }

    /**
     *
     */

    public Queue createQueue(String queueName)
        throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createQueue(queueName);
    }

    /**
     *
     */
    public StreamMessage createStreamMessage() throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createStreamMessage();
    }

    /**
     *
     */
    public TemporaryQueue createTemporaryQueue()
        throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createTemporaryQueue();
    }

    /**
     *
     */
    public TemporaryTopic createTemporaryTopic()
        throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createTemporaryTopic();
    }

    /**
     *
     */
    public TextMessage createTextMessage() throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createTextMessage();
    }

    /**
     *
     */
    public TextMessage createTextMessage(String text) throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createTextMessage(text);
    }

    /**
     *
     */
    public Topic createTopic(String topicName)
        throws JMSException{
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().createTopic(topicName);
    }

    /**
     *
     */
    public MessageListener getMessageListener() throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().getMessageListener();
    }

    /**
     *
     */
    public boolean getTransacted() throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().getTransacted();
    }

    /**
     *
     */
    public int getAcknowledgeMode() throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        return getMOMSession().getAcknowledgeMode();
    }


    /**
     *
     */
    public void recover() throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        throw new JMSException("JSession: recover Operation Not Allowed");
    }

    /**
     *
     */
    public void rollback() throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        throw new JMSException("JSession: rollback Operation Not Allowed");
    }

    /**
     *
     */
    public void run() {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        try {
            getMOMSession().run();
        } catch (JMSException e) {
            TraceJms.logger.log(BasicLevel.ERROR, "exception: "+e);
        }
    }

    /**
     *
     */
    public void setMessageListener(MessageListener listener) throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        getMOMSession().setMessageListener(listener);
    }


    /**
     *
     */
    public void unsubscribe(String name)
        throws JMSException {
        TraceJms.logger.log(BasicLevel.DEBUG, "");
        getMOMSession().unsubscribe(name);
    }


    // -----------------------------------------------------------------------
    // Synchronization Implementation
    // -----------------------------------------------------------------------

    /**
     * called by the transaction manager prior to the start
     * of the transaction completion process
     */
    public void beforeCompletion() {
        if(TraceJms.isDebug()){
            TraceJms.logger.log(BasicLevel.DEBUG, "");
        }
    }

    /**
     * called by the transaction manager after the transaction
     * is committed or rolled back.
     */

    public void afterCompletion(int status) {
        if(TraceJms.isDebug()){
            TraceJms.logger.log(BasicLevel.DEBUG, "");
        }
        txover = true;
        if (closed) {
            PhysicalClose();
        }
    }


}

