package astri.test.testPingComp1Impl;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.logging.Logger;

public class pingResourseIP {
	
	// Sends ping request to a provided IP address
		private static Logger m_logger = null;
		private static String m_resourceName=null;
		private static String m_ipAddress=null;
		private InetAddress m_addr = null;
		
		public pingResourseIP(Logger logger, String resource, String ipAddress) throws UnknownHostException {
		m_logger = logger;
		m_resourceName =resource;
		m_ipAddress=ipAddress;
		m_addr = InetAddress.getByName(m_ipAddress);
		}

	  public boolean sendPingRequest()
	              throws UnknownHostException, IOException
	  {
	    
	    m_logger.info("Sending Ping Request to :"+m_addr.getHostName() +":"+ m_ipAddress);
	    if (m_addr.isReachable(5000)) {
	    	m_logger.info(m_resourceName+" is reachable");
	    	return true;
	    }
	    else {
	    	m_logger.info(m_resourceName +" is unreachable");
	    	return false;
	    }
	  }
	  
	  /*Checks if a server is listening on a port*/
	  
	 public boolean isSocketAlive(int port, int timeout) {
			boolean isAlive = false;
	 
			// Creates a socket address from a hostname and a port number
			SocketAddress socketAddress = new InetSocketAddress(m_addr.getHostName(),port);
			Socket socket = new Socket();
			m_logger.info("checking hostName: " + m_addr.getHostName() + ", port: " + port);
			try {
				socket.connect(socketAddress, timeout);
				socket.close();
				isAlive = true;
				m_logger.info(m_addr.getHostName() + ":" + port + " is alive");
			} catch (SocketTimeoutException exception) {
				m_logger.info("SocketTimeoutException " + m_addr.getHostName() + ":" + port + ". " + exception.getMessage());
			} catch (IOException exception) {
				m_logger.info(
						"IOException - Unable to connect to " + m_addr.getHostName()+ ":" + port + ". " + exception.getMessage());
			}
			return isAlive;
		}
}
