/* 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.pool;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

public class PoolManager {

    private static Map pools = new HashMap();
    private static Map indexablePools = new HashMap();

    /**
     * create a object pool with the poolable object factory
     *
     * @param factory
     * @return
     */
    public static ObjectPool createPool(ObjectFactory factory) {
        ObjectPool pool = new SimpleObjectPool(factory);
        synchronized(pools) {
            pools.put(factory.getClass(), pool);
        }
        return pool;
    }

    /**
     * obtain a object pool , when not exists, will create one
     *
     * @param factory
     * @return
     */
    public static ObjectPool obtainPool(ObjectFactory factory) {
        synchronized(pools) {
            if(existsPool(factory.getClass())) {
                return (ObjectPool) pools.get(factory.getClass());
            }
            else {
                return createPool(factory);
            }
        }
    }

    public static boolean existsPool(Class factoryClass) {
        synchronized(pools) {
            return pools.containsKey(factoryClass);
        }
    }

    /**
     * create a object pool with the poolable object factory
     *
     * @param factory
     * @return
     */
    public static IndexableObjectPool createIndexablePool(ObjectFactory factory) {
        IndexableObjectPool pool = new SimpleIndexableObjectPool(factory);
        synchronized(indexablePools) {
            indexablePools.put(factory.getClass(), pool);
        }
        return pool;
    }

    /**
     * obtain a object pool , when not exists, will create one
     *
     * @param factory
     * @return
     */
    public static IndexableObjectPool obtainIndexablePool(ObjectFactory factory) {
        synchronized(indexablePools) {
            if(existsPool(factory.getClass())) {
                return (IndexableObjectPool) indexablePools.get(factory.getClass());
            }
            else {
                return createIndexablePool(factory);
            }
        }
    }

    public static boolean existsIndexablePool(Class factoryClass) {
        synchronized(indexablePools) {
            return indexablePools.containsKey(factoryClass);
        }
    }

    public static synchronized List pools() {
        List allPools = new ArrayList(pools.size() + indexablePools.size());
        allPools.addAll(pools.values());
        allPools.addAll(indexablePools.values());
        return Collections.unmodifiableList(allPools);
    }


    public static void main(String[] args) {

    }
}
