package org.postgresql.jdbc3;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

import org.postgresql.jdbc3.CacheConnection.PStmtKey;

public class StatementPool
{
    private Map map = null;
    CacheConnection conn = null;
    
    public StatementPool( CacheConnection conn )
    {
        this.conn = conn;
        map = new Hashtable();
    }
    
    public synchronized PreparedStatement getStatement( PStmtKey key ) throws SQLException 
    {
        CacheablePreparedStatement pstmt = (CacheablePreparedStatement)map.get( key );
        
        if ( pstmt  == null )
        {
            
            if(null == key._resultSetType && null == key._resultSetConcurrency) 
            {
                pstmt = new CacheablePreparedStatement(this, key, conn, key._sql );
            } 
            
            else 
            {
                pstmt = new CacheablePreparedStatement( this, key, conn, key._sql,
                        key._resultSetType.intValue(),
                        key._resultSetConcurrency.intValue(),
                        key._resultSetHoldability == null? ResultSet.CLOSE_CURSORS_AT_COMMIT:key._resultSetHoldability.intValue() 
                        );
            }
            
        }
        pstmt.setClosed(false);
        return pstmt;
    }
    
    public synchronized void returnStatement( CacheablePreparedStatement pstmt )    
    {
        try
        {            
            pstmt.clearParameters();
            pstmt.clearWarnings();
            
            // this really isn't necessary but I don't want to depend on execute doing this
            ((Jdbc3PreparedStatement)pstmt).closeResultSets();
            
            map.put( pstmt.key, pstmt );
        }
        catch( SQLException ex )
        {
            
        }
    }
    public int getNumIdle( Object key )
    {
        return 0;
    }
    public int getNumActive( Object key )
    {
        return 0;
    }
    
    public void close() throws SQLException
    {
        Iterator i = map.values().iterator();
        while ( i.hasNext() )
        {
            ((Jdbc3PreparedStatement)i.next()).close();
        }
    }
}
