/*
 * JORAM: Java(TM) Open Reliable Asynchronous Messaging
 * Copyright (C) 2012 - 2025 ScalAgent Distributed Technologies
 * Copyright (C) 2004 Bull SA
 *
 * 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.
 *
 * Initial developer(s): Frederic Maistre (Bull SA)
 * Contributor(s): Nicolas Tachker (Bull SA)
 */
package org.objectweb.joram.client.connector;

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.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 org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

import fr.dyade.aaa.common.Debug;

/**
 * An <code>OutboundSession</code> instance wraps a JMS session (XA or not)
 * for a component involved in outbound messaging.
 */
public class OutboundSession implements Session {
  private static final Logger logger = Debug.getLogger(OutboundSession.class.getName());
  private static final boolean DEBUG = logger.isLoggable(BasicLevel.DEBUG);
  
  /** The <code>OutboundConnection</code> the session belongs to. */
  protected OutboundConnection cnx;
  /** The wrapped JMS session. */
  Session sess;

  /** <code>true</code> if this "handle" is valid. */
  boolean valid = true;

  /** <code>true</code> if the session is started. */
  boolean started = false;

  protected boolean transacted;

  /**
   * Constructs an <code>OutboundSession</code> instance.
   */
  OutboundSession(Session sess, OutboundConnection cnx) {
    this.sess = sess;
    this.cnx = cnx;
    cnx.sessions.add(this);

    if (DEBUG)
      logger.log(BasicLevel.DEBUG, "OutboundSession(" + sess + ", " + cnx + ") cnx.sessions = " +  cnx.sessions);
  }
 
  /**
   * Constructs an <code>OutboundSession</code> instance.
   */
  OutboundSession(Session sess,  OutboundConnection cnx, boolean transacted) {
    this.sess = sess;
    this.cnx = cnx;
    this.transacted = transacted;
    cnx.sessions.add(this);

    if (DEBUG)
      logger.log(BasicLevel.DEBUG, "OutboundSession(" + sess + ", " + cnx + ", " + transacted + ") cnx.sessions = " +  cnx.sessions);
  }

  /**
   * return started value.
   */
  public boolean isStarted() {
    return started;
  }

  /** 
   * set started = true 
   */
  void start() {
   if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " start() started = true");

    started = true;
  }

  /** Checks the validity of the session. */
  void checkValidity() throws IllegalStateException {
    boolean validity;

    // TODO (AF): JORAM-335, should never happened?
//    if ((cnx == null) || (sess == null))
//      throw new IllegalStateException("Invalid state: session is invalid.");

    if (! valid)
      validity = false;
    else
      validity = cnx.valid;


    if (! validity)
      throw new IllegalStateException("Invalid state: session is closed.");
  }
  
  public String toString() {
    return "Outbound [" + sess + "]@" + hashCode();
  }

  // ************************************************************
  // Session implementation
  // ************************************************************

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public int getAcknowledgeMode() throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " getAcknowledgeMode() = " + sess.getAcknowledgeMode());
    
    checkValidity();
    if (transacted)
      return Session.SESSION_TRANSACTED;
    return sess.getAcknowledgeMode();
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public boolean getTransacted() throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " getTransacted() = " + ((sess == null)?"invalid":sess.getTransacted()));

    checkValidity();
    return sess.getTransacted();
  }

  /**
   * Forbidden call on a component's outbound session, throws a 
   * <code>IllegalStateException</code> instance.
   */
  @Override
  public void setMessageListener(MessageListener messageListener) throws JMSException {
    checkValidity();
    throw new IllegalStateException("Forbidden call on a component's session.");
  }

  /**
   * Forbidden call on a component's outbound session, throws a 
   * <code>IllegalStateException</code> instance.
   */
  @Override
  public MessageListener getMessageListener() throws JMSException {
    checkValidity();
    throw new IllegalStateException("Forbidden call on a component's session.");
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public Message createMessage() throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createMessage()");

    checkValidity();
    return sess.createMessage();
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
   @Override
  public TextMessage createTextMessage() throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createTextMessage()");

    checkValidity();
    return sess.createTextMessage();
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public TextMessage createTextMessage(String text) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createTextMessage(" + text + ")");

    checkValidity();
    return sess.createTextMessage(text);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public BytesMessage createBytesMessage() throws JMSException {
    checkValidity();
    return sess.createBytesMessage();
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public MapMessage createMapMessage() throws JMSException {
    checkValidity();
    return sess.createMapMessage();
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public ObjectMessage createObjectMessage() throws JMSException {
    checkValidity();
    return sess.createObjectMessage();
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public ObjectMessage createObjectMessage(java.io.Serializable obj) throws JMSException {
    checkValidity();
    return sess.createObjectMessage(obj);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public StreamMessage createStreamMessage() throws JMSException {
    checkValidity();
    return sess.createStreamMessage();
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public QueueBrowser createBrowser(Queue queue, String selector) throws JMSException {
    checkValidity();
    return sess.createBrowser(queue, selector);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public QueueBrowser createBrowser(Queue queue) throws JMSException {
    checkValidity();
    return sess.createBrowser(queue);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
   @Override
  public MessageProducer createProducer(Destination dest) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createProducer(" + dest + ")");
    
    checkValidity();
    return new OutboundProducer(sess.createProducer(dest), this);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public MessageConsumer createConsumer(Destination dest, String selector, boolean noLocal) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG,
                 this + " createConsumer(" + dest + ", " + selector + ", " + noLocal + ")");

    checkValidity();
    return new OutboundConsumer(sess.createConsumer(dest, selector, noLocal), this);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public MessageConsumer createConsumer(Destination dest, String selector) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createConsumer(" + dest + ", " + selector + ")");

    checkValidity();
    return new OutboundConsumer(sess.createConsumer(dest, selector), this);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public MessageConsumer createConsumer(Destination dest) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createConsumer(" + dest + ")");

    checkValidity();
    return new OutboundConsumer(sess.createConsumer(dest), this);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public TopicSubscriber createDurableSubscriber(Topic topic, String name, String selector, boolean noLocal) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, 
                 this + " createDurableSubscriber(" + topic + ", " + name + ", " + selector + ", " + noLocal + ")");

    checkValidity();

    TopicSubscriber sub = sess.createDurableSubscriber(topic, name, selector, noLocal);

    return new OutboundSubscriber(topic, noLocal, sub, this);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public TopicSubscriber createDurableSubscriber(Topic topic, String name) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createDurableSubscriber(" + topic + ", " + name + ")");

    checkValidity();

    TopicSubscriber sub = sess.createDurableSubscriber(topic, name);
    return new OutboundSubscriber(topic, false, sub, this);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public Queue createQueue(String queueName) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createQueue(" + queueName + ")");

    checkValidity();
    return sess.createQueue(queueName);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public Topic createTopic(String topicName) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createTopic(" + topicName + ")");

    checkValidity();
    return sess.createTopic(topicName);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public TemporaryQueue createTemporaryQueue() throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createTemporaryQueue()");

    checkValidity();
    return sess.createTemporaryQueue();
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public TemporaryTopic createTemporaryTopic() throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createTemporaryTopic()");

    checkValidity();
    return sess.createTemporaryTopic();
  }

  /** Method never used by a component, does nothing. */
  @Override
  public void run() {}

  /**
   * Forbidden call on a component's outbound session, throws a 
   * <code>IllegalStateException</code> instance.
   */
  @Override
  public void commit() throws JMSException {
    checkValidity();
    throw new IllegalStateException("Forbidden call on a component's session.");
  }

  /**
   * Forbidden call on a component's outbound session, throws a 
   * <code>IllegalStateException</code> instance.
   */
  @Override
  public void rollback() throws JMSException {
    checkValidity();
    throw new IllegalStateException("Forbidden call on a component's session.");
  }

  /** 
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public void recover() throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " recover()");

    checkValidity();
    sess.recover();
  }


  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public void unsubscribe(String name) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " unsubscribe(" + name + ")");

    checkValidity();
    sess.unsubscribe(name);
  }

  /** 
   * In Java EE, closing of the session occurs while closing
   * the component's connection.
   */
  @Override
  public void close() throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " close()");

    valid = false;
    cnx.sessions.remove(this);
    started = false;
    
    // This session is shared by all the outbound sessions.
    // This session will be closed on outbound connection close. 
    sess = null;
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createSharedConsumer(" + topic + ", " + sharedSubscriptionName + ")");
    checkValidity();
    return new OutboundConsumer(sess.createSharedConsumer(topic, sharedSubscriptionName), this);
  }

  @Override
  public MessageConsumer createSharedConsumer(Topic topic, String sharedSubscriptionName, String messageSelector) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createSharedConsumer(" + topic + ", " + sharedSubscriptionName + ", " + messageSelector + ")");
    checkValidity();
    return new OutboundConsumer(sess.createSharedConsumer(topic, sharedSubscriptionName, messageSelector), this);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public MessageConsumer createDurableConsumer(Topic topic, String name) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createDurableConsumer(" + topic + ", " + name + ")");
    checkValidity();
    return new OutboundConsumer(sess.createDurableConsumer(topic, name), this);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public MessageConsumer createDurableConsumer(Topic topic, String name, String messageSelector, boolean noLocal) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createDurableConsumer(" + topic + ", " + name + ", " + messageSelector + ", " + noLocal + ")");
    checkValidity();
    return new OutboundConsumer(sess.createDurableConsumer(topic, name, messageSelector, noLocal), this);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public MessageConsumer createSharedDurableConsumer(Topic topic, String name) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createSharedDurableConsumer(" + topic + ", " + name + ")");
    checkValidity();
    return new OutboundConsumer(sess.createSharedDurableConsumer(topic, name), this);
  }

  /**
   * Delegates the call to the wrapped JMS session.
   */
  @Override
  public MessageConsumer createSharedDurableConsumer(Topic topic, String name, String messageSelector) throws JMSException {
    if (DEBUG)
      logger.log(BasicLevel.DEBUG, this + " createSharedDurableConsumer(" + topic + ", " + name + ", " + messageSelector + ")");
    checkValidity();
    return new OutboundConsumer(sess.createSharedDurableConsumer(topic, name, messageSelector), this);
  }
}
