package com.eactive.eai.util;

import java.util.TimerTask;

import org.apache.commons.lang3.StringUtils;

import com.eactive.eai.common.server.EAIServerManager;
import com.eactive.eai.common.server.EAIServerVO;
import com.eactive.eai.common.util.Logger;

// HealthCheckManager에 등록된 HealthCheck Beans를 일정 주기로 실행
public class HealthCheckRunner extends TimerTask {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	private HealthCheckManager manager;

	public HealthCheckRunner() {
	}

	public void setHealthCheckManager(HealthCheckManager manager) {
		this.manager = manager;
	}

	public void run() {
		EAIServerManager mgr = EAIServerManager.getInstance();
		EAIServerVO server = mgr.getEAIServer(mgr.getLocalServerName());
		if (server == null) {
			return;
		}
		String instId = server.getFailoverSvr();

		if (StringUtils.isBlank(instId)) {
			logger.warn("HealthCheckRunner] FailOver Server instance not set - " + mgr.getLocalServerName());
			return;
		}

		boolean isAlive = ServerPingUtil.pingHost(instId);

		if (isAlive) {
			this.manager.addFailCount(instId, 0);
		} else {
			this.manager.addFailCount(instId, 1);
		}
	}
}
