package adaptive;

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

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

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

	private float thresholdSmaller, thresholdBigger;

	ReceiverFileMonitor rfm;

	public ReceiverMonitor(
		float thres1,
		float thres2,
		String host,
		String procFile) {
		thresholdBigger = thres1;
		thresholdSmaller = thres2;
		this.host = host;
		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();
	}

	void sendAdaptiveRequest(int status) {
		String tmp = new String();
		tmp += status;
		byte[] buf = tmp.getBytes();

		DatagramPacket packet;
		try {
			packet =
				new DatagramPacket(
					buf,
					buf.length,
					InetAddress.getByName(host),
					port);
			socket.send(packet);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	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;

			//			if ((linkStatus > threshold) || counter<10)
			//				sendAdaptiveRequest(1);
			//			else
			//				sendAdaptiveRequest(0);
			//			if (counter<10){
			//				sendAdaptiveRequest(0);
			//			}
			//			else 
			if (linkSignalNoiseRatio < thresholdSmaller) {
				sendAdaptiveRequest(2);
			} else if (linkSignalNoiseRatio < thresholdBigger) {
				sendAdaptiveRequest(1);
			} else
				sendAdaptiveRequest(0);

			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());

	}
}