package com.dbs.mplus.listener;

import java.util.Iterator;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.dbs.mplus.MPlusConstants;
import com.dbs.mplus.MPlusConstants.HOSPITAL;
import com.dbs.mplus.framework.FrameworkConstants;
import com.dbs.mplus.framework.service.menu.ServiceMenu;
/**
 * context가 refresh될 때 필요한 상수나 환경설정 값을 출력하여 deploy 담당자가 내용을 한번 더 확인할 수 있도록 하기 위함 
 * 
 * @author aple
 *
 */
public class MPlusServiceApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
	private static final Logger logger = LoggerFactory.getLogger(MPlusServiceApplicationListener.class);

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if(logger.isInfoEnabled()) {
			StringBuilder builder = new StringBuilder(); 
			
			builder.append(FrameworkConstants.NEW_LINE); 
			builder.append("병원 --------------------------------------------------------").append(FrameworkConstants.NEW_LINE); 
			
			HOSPITAL[] hospitals = MPlusConstants.HOSPITAL.values(); 
			if(hospitals != null) { 
				for(HOSPITAL h : hospitals) { 
					builder.append(h.name()).append(", ").append(h.getLinkUrl()).append(FrameworkConstants.NEW_LINE); 
				}
			}
					
			builder.append("메뉴 --------------------------------------------------------").append(FrameworkConstants.NEW_LINE); 			
			ApplicationContext ctx = event.getApplicationContext(); 
			Map<String, Object> ctrlMap = ctx.getBeansWithAnnotation(ServiceMenu.class); 
			
			if(ctrlMap != null) { 
				Iterator<Object> ctrlIter = ctrlMap.values().iterator(); 
				ServiceMenu serviceMenu = null; 
				Object ctrlObj = null; 
				
				while(ctrlIter.hasNext()) {
					ctrlObj = ctrlIter.next(); 
					serviceMenu = (ServiceMenu) ctrlObj.getClass().getAnnotation(ServiceMenu.class);  
					builder.append(serviceMenu.menuId()).append(" - ").append(serviceMenu.description()).append(FrameworkConstants.NEW_LINE); 
				}
			}
			
			logger.info(builder.toString());
		}
	}
}
