/*
 * 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
 *
 * Initial developer(s): Eric HARDESTY
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.ee.jdbc;


import java.sql.DriverManager;
import java.sql.SQLException;

import javax.resource.ResourceException;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ResourceAllocationException;
import javax.resource.spi.security.PasswordCredential;
import javax.security.auth.Subject;

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

public class DriverManagerMCFImpl
        extends ManagedConnectionFactoryImpl {

    @Override
    public ManagedConnection createManagedConnection(final Subject subject,
                                                      final ConnectionRequestInfo cxReq)
              throws ResourceException {

        if (trace.isLoggable(BasicLevel.DEBUG)) {
            trace.log(BasicLevel.DEBUG,"subject:"+subject+" connectionRequest:"+cxReq);
        }
      PasswordCredential pc = getPasswordCredential(this, subject, cxReq, pw);
      String clsName = null;
      DriverWrapper dWrap = null;
      try
      {
          clsName = mcfData.getMCFData(MCFData.DSCLASS);
          ClassLoader loader = this.getClass().getClassLoader();
          java.sql.Driver d = (java.sql.Driver) Class.forName(clsName, true, loader).newInstance();
          dWrap = new DriverWrapper(d);
          DriverManager.registerDriver(dWrap);
      }
      catch(ClassNotFoundException cnfe)
      {
          // Fallback: try TCCL
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            java.sql.Driver d = (java.sql.Driver) Class.forName(clsName, true, loader).newInstance();
            dWrap = new DriverWrapper(d);
            DriverManager.registerDriver(dWrap);
        } catch (Exception e) {
            throw new ResourceException("Class Name not found:" + clsName, e);
        }
      }
      catch(Exception ex)
      {
          throw new ResourceException("Error loading driver manager: " + clsName+" "+ex.getMessage(), ex);
      }

      java.sql.Connection connection = null;
      try {
          String val = null;
          if ((val = mcfData.getMCFData(MCFData.LOGINTIMEOUT)) != null) {
              if (val.length() > 0) {
                  DriverManager.setLoginTimeout(Integer.parseInt(val));
              }
          }
          if(cxReq != null) {
              ConnectionRequestInfoImpl cx = (ConnectionRequestInfoImpl) cxReq;
              connection = DriverManager.getConnection(mcfData.getMCFData(MCFData.URL),
                                                       cx.getUser(), cx.getPassword());
          } else if (pc != null){
              connection = DriverManager.getConnection(mcfData.getMCFData(MCFData.URL),
                                            pc.getUserName(), new String(pc.getPassword()));
          } else {
              connection = DriverManager.getConnection(mcfData.getMCFData(MCFData.URL),
                                                       mcfData.getMCFData(MCFData.USER),
                                                       mcfData.getMCFData(MCFData.PASSWORD));
          }
      }
      catch(SQLException sqle)
      {
          sqle.printStackTrace();
          throw new ResourceAllocationException("The connection could not be allocated: " + sqle.getMessage(), sqle);
      }
      catch(Exception ex)
      {
          ex.printStackTrace();
          throw new ResourceAllocationException("Error on allocation: " + ex.getMessage(), ex);
      }
      ManagedConnectionImpl mci = new ManagedConnectionImpl(this, pc, connection, null, null, dWrap);
      if (trace.isLoggable(BasicLevel.DEBUG)) {
          trace.log(BasicLevel.DEBUG, "Create Mc="+mci+" with connection="+connection);
      }
      return mci;
    }

    /* Determine if the factories are equal
     */
    @Override
    public boolean equals(final Object obj) {
        if (obj instanceof DriverManagerMCFImpl) {
            return mcfData.equals(((DriverManagerMCFImpl)obj).mcfData);
        }
        else {
            return false;
        }
    }

}