/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.esr.service.impl;

// Java classes
import java.util.Map;
import java.util.Iterator;
import java.util.List;

// Library classes
import org.apache.commons.lang.Validate;

// Framework classes
import gov.va.med.fw.model.lookup.AbstractLookup;
import gov.va.med.fw.service.AbstractComponent;

// EDB classes
import gov.va.med.esr.common.persistent.lookup.LookupsDAO;

/**
 * Project: Common
 * 
 * @author DNS   LEV
 * @version 1.0
 */
public class PreloadLookupDataServiceImpl extends AbstractComponent implements Runnable {

    private Map daoMap = null;
    
    /**
     * A default constructor  
     */
    public PreloadLookupDataServiceImpl() {
        super();
    }

    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
        Validate.notNull( daoMap, "Missing required lookup dao map" );
    }

    /**
     * Preload all lookup data in background thread
     * @see java.lang.Runnable#run()
     */
    public void run() {
        // Simply iterate through a list of lookup dao to preload lookup data
        for( Iterator i=daoMap.keySet().iterator(); i.hasNext(); ) {
            Object key = i.next();
            Object value = daoMap.get( key );
            if( value instanceof LookupsDAO ) {
                try {
                	Class lookupClass = Class.forName(key.toString());
                    List lookupList = ((LookupsDAO)value).findAll(lookupClass);
                    for( Iterator il=lookupList.iterator(); il.hasNext(); ) {
                        Object obj = il.next();
                        if( obj instanceof AbstractLookup ) {
                            ((LookupsDAO)value).getByCode(lookupClass, ((AbstractLookup)obj).getCode() ); 
                        }
                    }
                }
                catch( Exception e ) {
                    logger.error( "Failed to preload data for " + key, e );
                }
            }
        }
    }
    
    /**
     * @return Returns the daoMap.
     */
    public Map getDaoMap() {
        return daoMap;
    }
    /**
     * @param daoMap The daoMap to set.
     */
    public void setDaoMap(Map daoMap) {
        this.daoMap = daoMap;
    }
}