package adaptive;

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

public class SenderMonitor extends Thread {

	public long lastReport = System.currentTimeMillis();
	public int lastStatus, currentStatus = 0;
	public int effectiveStatus = 0;

	public void run() {
		try {
			DatagramSocket feedbackSocket = new DatagramSocket(6788);
			byte[] buf = new byte[100];
			DatagramPacket packet = new DatagramPacket(buf, buf.length);

			while (true) {
				feedbackSocket.receive(packet);
				
				lastStatus = currentStatus; 
				currentStatus = (new Integer(new String(packet.getData()).trim())).intValue();
				lastReport = System.currentTimeMillis();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public int getStatus() {
		if ((lastReport + 3000) < System.currentTimeMillis()){
			lastStatus = currentStatus;
			currentStatus = 3; //Timeout
		}
		
		if (lastStatus == currentStatus){
			effectiveStatus = currentStatus;
		}

		return effectiveStatus;
	}
}
