/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2007 Bull S.A.S.
 * 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: DataSourceFactory.java 21566 2011-08-08 12:28:12Z cazauxj $
 * --------------------------------------------------------------------------
 */


package org.ow2.jonas.dbm.internal.cm.naming;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
import javax.sql.DataSource;

import org.ow2.jonas.dbm.internal.DBMConstants;
import org.ow2.jonas.dbm.internal.cm.ConnectionManager;
import org.ow2.jonas.lib.util.Log;

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

/**
 * @author Philippe Durieux
 * Contributor(s):
 * <p>
 * 03/05/23 Adriana Danes - Introduce connection pool size configuration
 */
public class DataSourceFactory implements ObjectFactory {

    /**
     * Factory logger.
     */
    private static Logger logger = null;

    /**
     * Returns a {@link DataSource} from the given {@link Reference}.
     * @see javax.naming.spi.ObjectFactory#getObjectInstance(java.lang.Object, javax.naming.Name, javax.naming.Context, java.util.Hashtable)
     */
    public Object getObjectInstance(Object refObj, Name name, Context nameCtx, Hashtable env) throws Exception {

        Reference ref = (Reference) refObj;
        String clname = ref.getClassName();
        if (logger == null) {
            logger = Log.getLogger(Log.JONAS_DBM_PREFIX);
        }
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }

        // Old fashioned Connection Manager
        if (clname.equals(ConnectionManager.class.getName())) {
            String dsname = (String) ref.get(DBMConstants.NAME).getContent();
            ConnectionManager ds = ConnectionManager.getConnectionManager(dsname);
            if (ds == null) {
                // The DataSource was not in this JOnAS Server: Create it.
                if (logger.isLoggable(BasicLevel.DEBUG)) {
                    logger.log(BasicLevel.DEBUG, "Creating a new Connection Manager for " + dsname);
                }
                try {
                    String jBase = System.getProperty("jonas.base");
                    if (jBase == null) {
                        //TODO : must be removed. A client can lookup a datasource without modifications
                        // pure client case
                        ds = new ConnectionManager(true);
                        ds.setDSName(dsname);
                        ds.setUrl((String) ref.get(DBMConstants.URL).getContent());
                        ds.setClassName((String) ref.get(DBMConstants.CLASSNAME).getContent());
                        ds.setUserName((String) ref.get(DBMConstants.USERNAME).getContent());
                        ds.setPassword((String) ref.get(DBMConstants.PASSWORD).getContent());
                        return ds;
                    }
                    //build a new datasource for another server
                    // TODO must pass the TransactionService
                    ds = new ConnectionManager(null);
                    ds.setDSName(dsname);
                    ds.setUrl((String) ref.get(DBMConstants.URL).getContent());
                    ds.setClassName((String) ref.get(DBMConstants.CLASSNAME).getContent());
                    ds.setUserName((String) ref.get(DBMConstants.USERNAME).getContent());
                    ds.setPassword((String) ref.get(DBMConstants.PASSWORD).getContent());
                    ds.setTransactionIsolation((String) ref.get(DBMConstants.ISOLATIONLEVEL).getContent());
                    ds.setMapperName((String) ref.get(DBMConstants.MAPPERNAME).getContent());
                    ds.poolConfigure((String) ref.get("connchecklevel").getContent(),
                                     (String) ref.get("connmaxage").getContent(),
                                     (String) ref.get("maxopentime").getContent(),
                                     (String) ref.get("connteststmt").getContent(),
                                     (String) ref.get("pstmtmax").getContent(),
                                     (String) ref.get("minconpool").getContent(),
                                     (String) ref.get("maxconpool").getContent(),
                                     (String) ref.get("maxwaittime").getContent(),
                                     (String) ref.get("maxwaiters").getContent(),
                                     (String) ref.get("samplingperiod").getContent(),
                                     (String) ref.get("adjustperiod").getContent());
                } catch (Exception e) {
                    logger.log(BasicLevel.ERROR, "DataSourceFactory error", e);
                }
            } else {
                // The DataSource is already in this JOnAS Server: Just return it.
            }
            return ds;
        }

        logger.log(BasicLevel.ERROR, "no object found for " + clname);
        return null;
    }
}
