/** 
 * 
 * Copyright 2004 Hiram Chirino
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/
package org.codehaus.activemq.ra;

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

import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.IllegalStateException;
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.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
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.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.activemq.Closeable;


/**
 * Acts as a pass through proxy for a JMS Session object.
 * It intercepts events that are of interest of the ActiveMQManagedConnection.
 *
 * @version $Revision: 1.1 $
 */
public class JMSSessionProxy implements Session, QueueSession, TopicSession {

	static final private Log log = LogFactory.getLog(JMSSessionProxy.class);
    private final ActiveMQManagedConnection managedConnection;
    boolean closed=false;
    private ArrayList closeables = new ArrayList();

	public JMSSessionProxy(ActiveMQManagedConnection managedConnection) {
		this.managedConnection = managedConnection;
    }

    /**
     * @throws JMSException
     */
    public void close() throws JMSException {
        cleanup();
    }

    /**
     * Called by the ActiveMQManagedConnection to invalidate this proxy.
     * @throws JMSException
     */
    public void cleanup() {
    	// Close all the closeables..
    	for (Iterator iter = closeables.iterator(); iter.hasNext();) {
			Closeable c = (Closeable) iter.next();
			try {
				c.close();
			} catch (JMSException e) {
				log.debug("Error in occured closing a JMS object: "+e,e);
			}
		}
    	closed=true;
    }

    /**
     * 
     */
    private Session getSession() throws JMSException {
        if (closed) {
            throw new IllegalStateException("The Session is closed");
        }
        return managedConnection.getPhysicalSession();
    }

    /**
     * @throws JMSException
     */
    public void commit() throws JMSException {
        getSession().commit();
    }

    /**
     * @param queue
     * @return
     * @throws JMSException
     */
    public QueueBrowser createBrowser(Queue queue) throws JMSException {
    	QueueBrowser browser = getSession().createBrowser(queue);;
    	closeables.add(browser);
        return browser; 
    }

    /**
     * @param queue
     * @param messageSelector
     * @return
     * @throws JMSException
     */
    public QueueBrowser createBrowser(Queue queue, String messageSelector)
            throws JMSException {
        QueueBrowser browser = getSession().createBrowser(queue, messageSelector);
    	closeables.add(browser);
        return browser;
    }

    /**
     * @return
     * @throws JMSException
     */
    public BytesMessage createBytesMessage() throws JMSException {
        return getSession().createBytesMessage();
    }

    /**
     * @param destination
     * @return
     * @throws JMSException
     */
    public MessageConsumer createConsumer(Destination destination)
            throws JMSException {
        MessageConsumer consumer = getSession().createConsumer(destination);
        closeables.add(consumer);
        return consumer;
    }

    /**
     * @param destination
     * @param messageSelector
     * @return
     * @throws JMSException
     */
    public MessageConsumer createConsumer(Destination destination,
                                          String messageSelector) throws JMSException {
        MessageConsumer consumer = getSession().createConsumer(destination, messageSelector);
        closeables.add(consumer);
        return consumer;
    }

    /**
     * @param destination
     * @param messageSelector
     * @param NoLocal
     * @return
     * @throws JMSException
     */
    public MessageConsumer createConsumer(Destination destination,
                                          String messageSelector, boolean NoLocal) throws JMSException {
        MessageConsumer consumer = getSession().createConsumer(destination, messageSelector, NoLocal);
        closeables.add(consumer);
        return consumer;        
    }

    /**
     * @param topic
     * @param name
     * @return
     * @throws JMSException
     */
    public TopicSubscriber createDurableSubscriber(Topic topic, String name)
            throws JMSException {
        TopicSubscriber consumer = getSession().createDurableSubscriber(topic, name);
        closeables.add(consumer);
        return consumer;
    }

    /**
     * @param topic
     * @param name
     * @param messageSelector
     * @param noLocal
     * @return
     * @throws JMSException
     */
    public TopicSubscriber createDurableSubscriber(Topic topic, String name,
                                                   String messageSelector, boolean noLocal) throws JMSException {
        TopicSubscriber consumer = getSession().createDurableSubscriber(topic, name, messageSelector,
                noLocal);
        closeables.add(consumer);
        return consumer;
    }

    /**
     * @return
     * @throws JMSException
     */
    public MapMessage createMapMessage() throws JMSException {
        return getSession().createMapMessage();
    }

    /**
     * @return
     * @throws JMSException
     */
    public Message createMessage() throws JMSException {
        return getSession().createMessage();
    }

    /**
     * @return
     * @throws JMSException
     */
    public ObjectMessage createObjectMessage() throws JMSException {
        return getSession().createObjectMessage();
    }

    /**
     * @param object
     * @return
     * @throws JMSException
     */
    public ObjectMessage createObjectMessage(Serializable object)
            throws JMSException {
        return getSession().createObjectMessage(object);
    }

    /**
     * @param destination
     * @return
     * @throws JMSException
     */
    public MessageProducer createProducer(Destination destination)
            throws JMSException {
        MessageProducer producer = getSession().createProducer(destination);
        closeables.add(producer);
        return producer;
    }

    /**
     * @param queueName
     * @return
     * @throws JMSException
     */
    public Queue createQueue(String queueName) throws JMSException {
        return getSession().createQueue(queueName);
    }

    /**
     * @return
     * @throws JMSException
     */
    public StreamMessage createStreamMessage() throws JMSException {
        return getSession().createStreamMessage();
    }

    /**
     * @return
     * @throws JMSException
     */
    public TemporaryQueue createTemporaryQueue() throws JMSException {
        return getSession().createTemporaryQueue();
    }

    /**
     * @return
     * @throws JMSException
     */
    public TemporaryTopic createTemporaryTopic() throws JMSException {
        return getSession().createTemporaryTopic();
    }

    /**
     * @return
     * @throws JMSException
     */
    public TextMessage createTextMessage() throws JMSException {
        return getSession().createTextMessage();
    }

    /**
     * @param text
     * @return
     * @throws JMSException
     */
    public TextMessage createTextMessage(String text) throws JMSException {
        return getSession().createTextMessage(text);
    }

    /**
     * @param topicName
     * @return
     * @throws JMSException
     */
    public Topic createTopic(String topicName) throws JMSException {
        return getSession().createTopic(topicName);
    }

    /**
     * @return
     * @throws JMSException
     */
    public int getAcknowledgeMode() throws JMSException {
        return getSession().getAcknowledgeMode();
    }

    /**
     * @return
     * @throws JMSException
     */
    public MessageListener getMessageListener() throws JMSException {
        return getSession().getMessageListener();
    }

    /**
     * @return
     * @throws JMSException
     */
    public boolean getTransacted() throws JMSException {
        return getSession().getTransacted();
    }

    /**
     * @throws JMSException
     */
    public void recover() throws JMSException {
        getSession().recover();
    }

    /**
     * @throws JMSException
     */
    public void rollback() throws JMSException {
        getSession().rollback();
    }

    /**
     * @param listener
     * @throws JMSException
     */
    public void setMessageListener(MessageListener listener)
            throws JMSException {
        getSession(); // .setMessageListener(listener);
    }


    /**
     * @param name
     * @throws JMSException
     */
    public void unsubscribe(String name) throws JMSException {
        getSession().unsubscribe(name);
    }

    /**
     * @param queue
     * @return
     * @throws JMSException
     */
    public QueueReceiver createReceiver(Queue queue) throws JMSException {
        QueueReceiver consumer = ((QueueSession) getSession()).createReceiver(queue);
        closeables.add(consumer);
        return consumer;
    }

    /**
     * @param queue
     * @param messageSelector
     * @return
     * @throws JMSException
     */
    public QueueReceiver createReceiver(Queue queue, String messageSelector)
            throws JMSException {
        QueueReceiver consumer = ((QueueSession) getSession()).createReceiver(queue, messageSelector);
        closeables.add(consumer);
        return consumer;
    }

    /**
     * @param queue
     * @return
     * @throws JMSException
     */
    public QueueSender createSender(Queue queue) throws JMSException {
        QueueSender producer = ((QueueSession) getSession()).createSender(queue);
        closeables.add(producer);
        return producer;
    }

    /**
     * @param topic
     * @return
     * @throws JMSException
     */
    public TopicPublisher createPublisher(Topic topic) throws JMSException {
        TopicPublisher producer = ((TopicSession) getSession()).createPublisher(topic);
        closeables.add(producer);
        return producer;
    }

    /**
     * @param topic
     * @return
     * @throws JMSException
     */
    public TopicSubscriber createSubscriber(Topic topic) throws JMSException {
        TopicSubscriber consumer = ((TopicSession) getSession()).createSubscriber(topic);
        closeables.add(consumer);
        return consumer;
    }

    /**
     * @param topic
     * @param messageSelector
     * @param noLocal
     * @return
     * @throws JMSException
     */
    public TopicSubscriber createSubscriber(Topic topic,
                                            String messageSelector, boolean noLocal) throws JMSException {
        TopicSubscriber consumer = ((TopicSession) getSession()).createSubscriber(topic, messageSelector, noLocal);
        closeables.add(consumer);
        return consumer;
    }

    /**
     * @see javax.jms.Session#run()
     */
    public void run() {
        throw new RuntimeException("Operation not supported.");
    }

}
