/*
 * JORAM: Java(TM) Open Reliable Asynchronous Messaging
 * Copyright (C) 2004 - 2022 ScalAgent Distributed Technologies
 *
 * 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.
 */
package org.ow2.joram.jakarta.connector;

import jakarta.jms.IllegalStateException;
import jakarta.jms.JMSException;
import jakarta.jms.JMSRuntimeException;
import jakarta.jms.JMSSecurityException;
import jakarta.jms.JMSSecurityRuntimeException;
import javax.naming.Reference;
import jakarta.resource.spi.ConnectionManager;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;
import org.ow2.joram.jakarta.jms.JMSContext;

import fr.dyade.aaa.common.Debug;

/**
 * An <code>OutboundConnectionFactory</code> instance is used for
 * getting a connection to an underlying JORAM server.
 */
public class OutboundConnectionFactory implements jakarta.jms.ConnectionFactory, java.io.Serializable, jakarta.resource.Referenceable {
  /** define serialVersionUID for interoperability */
  private static final long serialVersionUID = 1L;
  
  private static final Logger logger = Debug.getLogger(OutboundConnectionFactory.class.getName());
  
  /** Central manager for outbound connectivity. */
  protected ManagedConnectionFactoryImpl mcf;
  /** Manager for connection pooling. */
  protected ConnectionManager cxManager;

  /** Naming reference of this instance. */
  protected Reference reference;

  /**
   * Constructs an <code>OutboundConnectionFactory</code> instance.
   *
   * @param mcf        Central manager for outbound connectivity.
   * @param cxManager  Manager for connection pooling.
   */
  OutboundConnectionFactory(ManagedConnectionFactoryImpl mcf, ConnectionManager cxManager) {
    if (logger.isLoggable(BasicLevel.DEBUG))
      logger.log(BasicLevel.DEBUG, "OutboundConnectionFactory(" + mcf + 
                                    ", " + cxManager + ")");

    this.mcf = mcf;
    if (cxManager != null) {
      this.cxManager = cxManager;
    } else {
      this.cxManager = DefaultConnectionManager.getRef();
    }
  }

  // ************************************************************
  // Implementation of Referenceable
  // ************************************************************
  
  /** Sets the naming reference of this factory. */
  @Override
  public void setReference(Reference ref) {
    this.reference = ref;
  }

  /** Returns the naming reference of this factory. */
  @Override
  public Reference getReference()  {
    return reference;
  }

  // ************************************************************
  // Implementation of ConnectionFactory
  // ************************************************************

  /**
   * Requests a connection for the default user, eventually returns an
   * <code>OutboundConnection</code> instance.
   *
   * @exception JMSSecurityException   If connecting is not allowed.
   * @exception IllegalStateException  If the underlying JORAM server
   *                                   is not reachable.
   * @exception JMSException           Generic exception.
   */
  @Override
  public jakarta.jms.Connection createConnection() throws JMSException {
    if (logger.isLoggable(BasicLevel.DEBUG))
      logger.log(BasicLevel.DEBUG, this + " createConnection()");

    return createConnection(mcf.getUserName(), mcf.getPassword());
  }

  /**
   * Requests a connection for a given user, eventually returns an
   * <code>OutboundConnection</code> instance.
   *
   * @exception JMSSecurityException   If connecting is not allowed.
   * @exception IllegalStateException  If the underlying JORAM server
   *                                   is not reachable.
   * @exception JMSException           Generic exception.
   */
  @Override
  public jakarta.jms.Connection
      createConnection(String userName, String password) throws JMSException {

    if (logger.isLoggable(BasicLevel.DEBUG))
      logger.log(BasicLevel.DEBUG, this + " createConnection(" + userName + ", ****)");

    try {
      ConnectionRequest cxRequest = null;
      if (mcf instanceof ManagedQueueConnectionFactoryImpl)
        cxRequest = new QueueConnectionRequest(userName, password, mcf.getIdentityClass());
      else if (mcf instanceof ManagedTopicConnectionFactoryImpl)
        cxRequest = new TopicConnectionRequest(userName, password, mcf.getIdentityClass());
      else
        cxRequest = new ConnectionRequest(userName, password, mcf.getIdentityClass());

      if (logger.isLoggable(BasicLevel.DEBUG))
        logger.log(BasicLevel.DEBUG, this + " createConnection cxManager = " + cxManager);

      Object o = cxManager.allocateConnection(mcf, cxRequest);

      if (logger.isLoggable(BasicLevel.DEBUG))
        logger.log(BasicLevel.DEBUG, this + " createConnection connection = " + o);

      return (jakarta.jms.Connection) o;
    } catch (jakarta.resource.spi.SecurityException exc) {
      throw new JMSSecurityException("Invalid user identification: " + exc);
    } catch (jakarta.resource.spi.CommException exc) {
      throw new IllegalStateException("Could not connect to the JORAM server: "
                                      + exc);
    } catch (jakarta.resource.ResourceException exc) {
      throw new JMSException("Could not create connection: " + exc);
    }
  }

  @Override
  public jakarta.jms.JMSContext createContext() {
    try {
      return new JMSContext(createConnection());
    } catch (JMSSecurityException e) {
      logger.log(BasicLevel.ERROR, "Unable to create JMSContext", e);
      throw new JMSSecurityRuntimeException("Unable to create JMSContext", e.getMessage(), e);
    } catch (JMSException e) {
      logger.log(BasicLevel.ERROR, "Unable to create JMSContext", e);
      throw new JMSRuntimeException("Unable to create JMSContext", e.getMessage(), e);
    }
  }

  @Override
  public jakarta.jms.JMSContext createContext(String userName, String password) {
    try {
      return new JMSContext(createConnection(userName, password));
    } catch (JMSSecurityException e) {
      logger.log(BasicLevel.ERROR, "Unable to create JMSContext", e);
      throw new JMSSecurityRuntimeException("Unable to create JMSContext", e.getMessage(), e);
    } catch (JMSException e) {
      logger.log(BasicLevel.ERROR, "Unable to create JMSContext", e);
      throw new JMSRuntimeException ("Unable to create JMSContext", e.getMessage(), e);
    }
  }

  @Override
  public jakarta.jms.JMSContext createContext(String userName, String password, int sessionMode) {
    try {
      return new JMSContext(createConnection(userName, password), sessionMode);
    } catch (JMSSecurityException e) {
      logger.log(BasicLevel.ERROR, "Unable to create JMSContext", e);
      throw new JMSSecurityRuntimeException("Unable to create JMSContext", e.getMessage(), e);
    } catch (JMSException e) {
      logger.log(BasicLevel.ERROR, "Unable to create JMSContext", e);
      throw new JMSRuntimeException ("Unable to create JMSContext", e.getMessage(), e);
    }
  }

  @Override
  public jakarta.jms.JMSContext createContext(int sessionMode) {
    try {
      return new JMSContext(createConnection(), sessionMode);
    } catch (JMSSecurityException e) {
      logger.log(BasicLevel.ERROR, "Unable to create JMSContext", e);
      throw new JMSSecurityRuntimeException("Unable to create JMSContext", e.getMessage(), e);
    } catch (JMSException e) {
      logger.log(BasicLevel.ERROR, "Unable to create JMSContext", e);
      throw new JMSRuntimeException ("Unable to create JMSContext", e.getMessage(), e);
    }
  }
}
