package kr.gmtc.gw.eyegw.controller;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component("systemCheckManager")
public class SystemCheckManager {
	private final Logger logger = LoggerFactory.getLogger("scLogger");

	private ScheduledExecutorService scheduler;
	
	@Value("${sc.schduler.initialDelay:3}")
	private int initialDelay;
	
	@Value("${sc.schduler.fixedDelay:1}")
	private int fixedDelay;
	
	private final int REST_CNT = 10;
	private int ErrorCnt = REST_CNT;
	private String ErrorMsg = "";
	private int WarnCnt = REST_CNT;
	private String WarnMsg = "";
	
	
	@PostConstruct
	private void initialize() {
		CreateSchedules();
	}
    
	private void CreateSchedules() {
        
		scheduler = Executors.newScheduledThreadPool(1);
		
            Runnable ReconnTask = () -> {

            	if(ErrorCnt < REST_CNT) {
            		ErrorCnt++;            	
            		logger.error("ERROR|" + ErrorMsg);	
            	}
            	else if(WarnCnt < REST_CNT) {
            		WarnCnt++;            		
            		logger.warn("WARN|" + WarnMsg);
            	}
            	else {
                	logger.info("NORAML|Heartbeat");
            	}
            	
            };
    	    scheduler.scheduleAtFixedRate(ReconnTask, initialDelay, fixedDelay, TimeUnit.SECONDS);
	}
	
	public void error (String Msg) {
		logger.error("ERROR|" + Msg);
		
		ErrorCnt = 0;
		ErrorMsg = Msg;
	}
	
	public void warn(String Msg) {

    	if(ErrorCnt >= REST_CNT) 
    		logger.warn("WARN|" + Msg);
    	
		WarnCnt = 5;
		WarnMsg = Msg;
    }
	
	public void info (String Msg) {
		logger.info("NORMAL|" + Msg);
	}
	
	@PreDestroy
	public void finalize() {
        try {        	
        	scheduler.shutdown();
        	scheduler.awaitTermination(100, TimeUnit.MILLISECONDS);    		
		} catch (Exception e) {
			logger.error("", e);
		}
	}
}

