package com.eactive.eai.common.logger;

import com.eactive.eai.common.dao.DAOFactory;
import com.eactive.eai.common.logger.async.HttpAdapterExtraLogH2Factory;
import com.eactive.eai.common.util.ApplicationContextProvider;
import com.eactive.eai.common.util.Logger;

/**
 * 1. 기능 : DB 장애 상태 관리 
 * 2. 처리 개요 :  
 * 3. 주의사항
 */
public class EAIDBLogControl {
    static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
    
    private static boolean isEnable = true;
    
    private EAIDBLogControl() {
    	
    }
    
	public static synchronized boolean isEnable() {
		return isEnable;
	}

	public static synchronized void setEnable(boolean enable) {
		if (isEnable == enable) return ;
		isEnable = enable;
		if (!enable){
			//thread 기동
			Runnable runnable = new Runnable() {
				public void run() {
					while(true) {
						try {
							//db check
				            EAILogDAO dao = ApplicationContextProvider.getContext().getBean(EAILogDAO.class);
				            
				            boolean result  = dao.getCheck();
				            if (result){
				            	setEnable(result);
								// 25.04.29 안해도 정상적으로 Header 정보 저장됨 확인
								// 있으면 오히려 NoClassDefFoundError Exception 발생
//								HttpAdapterExtraLogH2Factory.getInstance().closeSessionFactory();
				            	break;
				            }
						} catch(Throwable t) {
							logger.warn("setEnable", t);
						}
						try {
							Thread.sleep(1000L);
						} catch(InterruptedException e) {
							logger.warn("sleep", e);
						}
					}
				}
			};
			Thread t = new Thread(runnable);
			t.setName("DBChecker-Launcher");
			t.start();				
		}
	}
}
