package pair;

import java.io.IOException;
import java.net.*;

import cc.Parameters;

public class Receiver extends Thread {
	public static void main(String args[]) {
		//Parse initial parameters
		Parameters.parseArgs(args);

		Receiver pairReceiver;
		try {
			pairReceiver = new Receiver();
			while (System.in.read() == -1);
			System.out.println("I am going...");
			pairReceiver.terminate();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	boolean finish = false;

	DatagramSocket socket = null;
	DatagramPacket packet = null;

	byte[] buf = null;

	Receiver() throws SocketException, UnknownHostException {
		socket = new DatagramSocket();
		//socket.setSoTimeout(Parameters.getTimeout() * 1000);

		buf = new byte[Parameters.getMaxSize()];

		packet = new DatagramPacket(buf, Parameters.getMaxSize());

		start();

		System.out.println("Ready at: " + getIP() + ":" + getPort());
	}

	public void terminate() {
		this.interrupt();
		finish = true;
	}

	public void run() {
		int counter = 0;
		long currentTime = 0, lastTime = System.currentTimeMillis();
		try {
			while (!finish) {
				socket.receive(packet);
				
				currentTime = System.currentTimeMillis();
				if (isPairPacket(packet)) {
					counter++;
					System.out.println(lastTime+ "\t" +currentTime+ "\t" + (currentTime - lastTime));
				}
				lastTime = currentTime;
			}
			socket.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean isPairPacket(DatagramPacket packet) {
		if (packet.getData()[0] == 'p' )
			return true;
		return false;
	}

	public int getPort() {
		return socket.getLocalPort();
	}

	public String getIP() {
		java.util.Enumeration interfaces;
		try {
			interfaces = NetworkInterface.getNetworkInterfaces();

			while (interfaces.hasMoreElements()) {
				java.util.Enumeration IPs =
					((NetworkInterface) (interfaces.nextElement()))
						.getInetAddresses();
				while (IPs.hasMoreElements()) {
					InetAddress IP = ((InetAddress) (IPs.nextElement()));
					if (!IP.isLinkLocalAddress() && !IP.isLoopbackAddress())
						return IP.getHostAddress();
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}

		return null;
	}
}
