package com.eactive.eai.adapter.http.healthcheck;

import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.eactive.eai.adapter.AdapterVO;
import com.eactive.eai.common.util.Logger;

public class HttpTargetMonitor extends TimerTask {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	private HttpTargetMonitorManager manager;

	public void setManager(HttpTargetMonitorManager manager) {
		this.manager = manager;
	}

	public void run() {
		logger.warn("HttpTargetMonitor] run");

		if (this.manager == null || !this.manager.isStarted()) {
			logger.warn("HttpTargetMonitorManager is stopped. stop HttpTargetMonitor.");
			return;
		}

		Iterator<String> adapterNames = manager.getAllAdapterNames();

		ExecutorService executor = Executors.newFixedThreadPool(20);
		try {
			while (adapterNames.hasNext()) {
				String name = adapterNames.next();
				HttpHealthChecker checker = manager.getHttpHeacthChecker(name);
				AdapterVO vo = checker.getAdapter();
				if (checker == null || vo == null) {
					logger.warn("Target HealthCheck remove - " + name);
					manager.removeHttpHeacthChecker(name);
				} else {
					executor.submit(() -> {
						try {
							vo.setStatus(checker.isAlive());
						} catch (Exception e) {
							if (logger.isError()) {
								logger.error("Target HealthCheck error", e);
							}
						}
					});
				}
			}
		} finally {
			executor.shutdown();
		}
	}
}
