package com.eactive.eai.util;

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

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class ServerPingUtil {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	public static boolean pingHost(String host, int port, int timeout) {
		try (Socket socket = new Socket()) {
			socket.connect(new InetSocketAddress(host, port), timeout);
			return true;
		} catch (IOException e) {
			logger.warn(String.format("ServerPingUtil] pingHost (host= %s, port=%d) Failed.", host, port));
			return false; // Either timeout or unreachable or failed DNS lookup.
		}
	}

	public static boolean pingHost(String instId) {
		boolean isAlive = true;
		EAIServerManager mgr = EAIServerManager.getInstance();
		EAIServerVO serverVo = mgr.getEAIServer(instId);

		// if not found, server is invalid
		if (serverVo == null) {
			logger.warn("ServerPingUtil] invalid eLink instId = " + instId);
			return false;
		}

		String address = serverVo.getAddress();
		int port = Integer.parseInt(serverVo.getPort());
		isAlive = pingHost(address, port, 3 * 1000);
		return isAlive;
	}

//	public static void main(String[] argv) throws Exception {
//		String host = "localhost";
//		int port = 10310;
//		int timeout = 3;
//		
//		boolean isAlive = pingHost(host, port, timeout);
//		System.out.println(">> Server Ping Test  ");
//		System.out.println(String.format("ServerPingUtil] pingHost (host= %s, port=%d) => %s",host, port, isAlive));
//
//    	HashMap<String, Integer> map = new HashMap<String, Integer>();
//    	
//    	Integer count = map.get("test");
//    	System.out.println(count);
//    	
//    	map.put("test", 10);
//    	count = map.get("test");
//    	System.out.println(count);
//	    
//	}
}
