package sfs.cluster.lobby.monitor;

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

/**
 * Performs the cluster node monitoring tasks
 */
public class NodeMonitorAgent implements Runnable
{
	IMonitorEventHandler monitorEventHandler;
	String addr;
	int port;
	
	public NodeMonitorAgent(IMonitorEventHandler monitorEventHandler, String addr, int port)
    {
		this.monitorEventHandler = monitorEventHandler;
		this.addr = addr;
		this.port = port; 
	}
	
	public void run()
	{
		try
		{
			InetAddress clusterNode = InetAddress.getByName(addr);
			
			// is the node responding to ping in the expected time?
			if (clusterNode.isReachable(ClusterMonitor.REQUIRED_PING_RESPONSE))
			{
				// let's see if a connection is possible
				Socket socket = new Socket(clusterNode, port);
				
				// cool, we should have connected, service should be up. Close the socket
				socket.close();
			}
			else
			{
				MonitorEvent event = new MonitorEvent(MonitorEvent.NODE_PING_FAILED);
				event.getParams().put("nodeId", addr + ":" + port);
				monitorEventHandler.handleMonitorEvent(event);
			}
		}
		catch (IOException ioError)
		{
			MonitorEvent event = new MonitorEvent(MonitorEvent.NODE_CONNECTION_FAILED);
			event.getParams().put("nodeId", addr + ":" + port);
			monitorEventHandler.handleMonitorEvent(event);
		}
		catch (Exception error) 
		{
			error.printStackTrace();
		}
	}
	
	
}
