package com.eactive.eai.rms.common.spring;

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

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.data.PortalSchemaProviderHolder;
import com.eactive.eai.rms.env.EmsConfig;

public class CustomBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    /**
    * Logger for this class
    */
	final Logger logger = Logger.getLogger(CustomBeanFactoryPostProcessor.class);
	    
	public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
			throws BeansException {

		// PortalSchemaProviderHolder 초기화 (Hibernate EntityManagerFactory 생성 전에 필요)
		PortalSchemaProviderHolder.setProvider(() -> System.getProperty(EmsConfig.TABLE_OWNER));
		if (logger.isDebugEnabled()) {
			logger.debug("PortalSchemaProviderHolder initialized with tableOwner: " + System.getProperty(EmsConfig.TABLE_OWNER));
		}

		List<DataSourceType> dataSourceTypes = new ArrayList<DataSourceType>();
		
		Map maps = factory.getBeansOfType(DataSourceType.class);
		Iterator iter = maps.keySet().iterator();
		while (iter.hasNext()) {
			String key = (String) iter.next();
			
			DataSourceType obj = (DataSourceType) factory.getBean(key);
			if (logger.isDebugEnabled()){
				logger.debug("dataSourceType key="+key + ", value="+ obj );
			}
			dataSourceTypes.add(obj);
		}
		
		DataSourceTypeManager.setDataSourceTypes(dataSourceTypes);
	
		
	}

}
