package fixed;

import java.net.*;

public class ReceiverMonitor extends Thread {
	private DatagramSocket socket;
	private int port;

	private long total = 0;
	private int count = 0;

	ReceiverFileMonitor rfm;

	public ReceiverMonitor(String procFile) {
		this.port = 6788;

		rfm = new ReceiverFileMonitor(procFile);

		try {
			socket = new DatagramSocket();
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

	public void update(int size) {
		total += size;
		//		rfm.update();
	}

	public void run() {
		long lastTimeStamp = System.currentTimeMillis();
		long lastTotal = 0;

		long currentTimeStamp;
		long currentTotal;

		while (true) {
			float linkSignalNoiseRatio = 0;
			try {
				rfm.update();
				linkSignalNoiseRatio += rfm.getSignalNoiseRatio();
				sleep(315);
				rfm.update();
				linkSignalNoiseRatio += rfm.getSignalNoiseRatio();
				sleep(315);
				rfm.update();
				linkSignalNoiseRatio += rfm.getSignalNoiseRatio();
				sleep(314);
				linkSignalNoiseRatio /= 3;

			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			currentTimeStamp = System.currentTimeMillis();
			currentTotal = total;
			print(
				currentTimeStamp,
				linkSignalNoiseRatio,
				lastTimeStamp,
				lastTotal,
				currentTimeStamp,
				currentTotal);

			lastTimeStamp = currentTimeStamp;
			lastTotal = currentTotal;
		}
	}

	private void print(
		long timeStamp,
		float signalNoiseRatio,
		long lastTimeStamp,
		long lastTotal,
		long currentTimeStamp,
		long currentTotal) {

		float rate =
			(float) (8 * (currentTotal - lastTotal))
				/ (1000 * (currentTimeStamp - lastTimeStamp));

		System.out.println(
			(count++)
				+ " "
				+ timeStamp
				+ " "
				+ rate * 100
				+ " "
				+ signalNoiseRatio
				+ " "
				+ rfm.getQuality()
				+ " "
				+ rfm.getSignal()
				+ " "
				+ rfm.getNoise());

	}
}