/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
package gov.va.med.esr.common.persistent.lookup;

import java.util.Map;
import java.util.Set;
import java.util.List;
import java.util.Iterator;

import org.springframework.core.CollectionFactory;
import gov.va.med.fw.service.config.InheritedMapFactoryBean;

/**
 * LookupsDAOMapFactoryBean created on May 19, 2006
 * @author DNS   LEV
 */
public class LookupsDAOMapFactoryBean extends InheritedMapFactoryBean {

	/**
	 * A default constructor
	 */
	public LookupsDAOMapFactoryBean() {
		super();
	}

	/**
	 * @see org.springframework.beans.factory.config.AbstractFactoryBean#createInstance()
	 */
	protected Object createInstance() {
		Object instance = super.createInstance();
      // A map in lookup_daos.xml has the following format
      /*
       * <map>
       *    <entry key-ref="DAOReference">
       *       <list>
       *          a collection of lookup classes that use the same dao for data retrieval
       *        </list>              
       *     </entry>
       * <map>
       * 
       * After flattening a map for easy retrieval of data, a map will 
       * be in the following format
       * <map>
       *    <entry key="fully qualified lookup class name">
       *       <ref bean="DAOReference"/>
       *    <entry>
       */
      
      // Flatten a map for easy retrieval
      // a key is a lookup class and a value is a dao bean
      Map map = instance instanceof Map ? (Map)instance : null;
      if( map != null ) {
         Map flatten = CollectionFactory.createLinkedMapIfPossible( 100 );
         Set daos = map.entrySet();
         Iterator i = daos != null ? daos.iterator() : null;
         while( i != null && i.hasNext() ) {
            Map.Entry entry = (Map.Entry)i.next();
            Object dao = entry.getKey();
            Object obj = entry.getValue();
            List lookups = obj instanceof List ? (List)obj : null;
            if( lookups != null ) {
               for( Iterator iter=lookups.iterator(); iter.hasNext(); ) {
                  Object lookup = iter.next();
                  flatten.put( lookup, dao );
               }
            }
         }
         
         // Keep the flatten map
         if( flatten.size() > 0 ) {
            map = flatten;
         }
      }
      
      return map;
	}
}