package org.mockejb;

import java.util.*;

import org.apache.commons.logging.*;

/**
 * Provides rudimentary in-memory entity database implementation.
 * Entities can be searched only by the primary key.
 * Users should populate EntityDatabase with the mock entities for their test. 
 * MockEJB searches EntityDatabase: 
 * 1) During the call to CMP findByPrimaryKey.
 * 2) After a BMP finder returns a PK or collection of PKs.
 * MockEJB automatically add an entity to this "database" if
 * its ejbCreate method returns a PK. 
 * 
 *  
 * @author Alexander Ananiev
 */
class EntityDatabaseImpl  implements EntityDatabase {
    
    // logger for this class
    private static Log logger =
        LogFactory.getLog(EntityDatabase.class.getName());
    
   
     
    EntityDatabaseImpl(){
        
    }

    private Map entityTypes = Collections.synchronizedMap( new HashMap() );
    
    
    public void add( Class homeIfaceClass, Object pk, Object entity ){
        
        logger.debug( "Adding entity for home "+homeIfaceClass.getName()+" with PK "+pk+
                " to entity storage" );
    
        Map entities = (Map)entityTypes.get( homeIfaceClass.getName() );
        if (entities == null) {
            entities = Collections.synchronizedMap( new HashMap() );
            entityTypes.put( homeIfaceClass.getName(), entities );
        }
        entities.put(pk, entity );    
    }
    
    public Object find( Class homeIfaceClass, Object pk ) {
        Object entity  = null;
        
        Map entities = (Map)entityTypes.get( homeIfaceClass.getName());
        if ( entities != null ){
            entity = entities.get( pk );
        }
        
        return entity;
    }
    
    
    public void clear() {
        entityTypes.clear();
    }
}