package cz.vutbr.feec.session.ping;

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

import org.apache.log4j.Logger;
import org.savarese.vserv.tcpip.ICMPEchoPacket;
import org.savarese.vserv.tcpip.OctetConverter;

public class PingEchoReplyListener implements IPingEchoReplyListener {
	private static Logger logger = Logger.getLogger(RttMeasurement.class.getName());
	private String hostname;
	private StringBuffer buffer = new StringBuffer(128);

	public PingEchoReplyListener(String hostname) {
		this.hostname = hostname;
	}
	
	private double minRtt = Double.MAX_VALUE; 

	public void notifyEchoReply(ICMPEchoPacket packet, byte[] data,
			int dataOffset, byte[] srcAddress) throws IOException {
		long end = System.nanoTime();
		long start = OctetConverter.octetsToLong(data, dataOffset);
		// Note: Java and JNI overhead will be noticeable (100-200
		// microseconds) for sub-millisecond transmission times.
		// The first ping may even show several seconds of delay
		// because of initial JIT compilation overhead.
		double rtt = (double) (end - start) / 1e6;

		buffer.setLength(0);
		buffer.append(packet.getICMPPacketByteLength()).append(" bytes from ")
				.append(hostname).append(" (");
		buffer.append(InetAddress.getByAddress(srcAddress).toString());
		buffer.append("): icmp_seq=").append(packet.getSequenceNumber())
				.append(" ttl=").append(packet.getTTL()).append(" time=")
				.append(rtt).append(" ms");
		
		if(minRtt > rtt) {
			minRtt = rtt;
		}
		
		logger.debug(buffer.toString());
		
	}

	/**
	 * Gets the minimal round trip time.
	 * 
	 * @return the minimal measured round trip time
	 */
	public double getMinRtt() {
		return minRtt;
	}
}
