/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */

package org.jfox.jdbc.datasource;

import java.util.Hashtable;
import java.util.Map;
import java.util.WeakHashMap;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

/**
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class DataSourceObjectFactory implements ObjectFactory {

    /**
     * remember datasources have looked up
     * if lookup twice, just return the origin
     * use WeakHashMap, if the datasource have destroyed, will automatic remove from the Map by GC
     */
    private static Map dataSources = new WeakHashMap();

    /**
     * Method that inherited from ObjectFactory.
     *
     * @param obj
     * @param name
     * @param nameCtx
     * @param environment
     * @return
     * @throws Exception
     */
    //TODO: use dsName to identity datasource

    public synchronized Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception {
        Object result = null;
        Reference ref = (Reference) obj;
        if(ref.getClassName().equals(PoolDataSource.class.getName())) {
            String _dsName = (String) ref.get("dsName").getContent();
            String _dbDriver = (String) ref.get("dbDriver").getContent();
            String _dbURL = (String) ref.get("dbURL").getContent();
            String _user = (String) ref.get("user").getContent();
            String _password = (String) ref.get("password").getContent();

            if(dataSources.containsKey(_dsName)) {
                return dataSources.get(_dsName);
            }
            else {
                int initNum = Integer.parseInt((String) ref.get("initNum").getContent());
                int maxRest = Integer.parseInt((String) ref.get("maxRest").getContent());
                PoolDataSource pds = new PoolDataSource(_dsName, _dbDriver, _dbURL, _user, _password);
                pds.setInitNum(initNum);
                pds.setMaxRest(maxRest);
                pds.init();
                dataSources.put(_dsName, pds);
                result = pds;
            }
        }
        return result;
    }

    static void removeDataSource(String dsName) {
        dataSources.remove(dsName);
    }

    public static void main(String[] args) {

    }
}