package auto;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class ReceiverSNRMonitor extends Thread {
	private String procFile;
	private float SNR = 0;
	private float maxSNR = 0;

	public ReceiverSNRMonitor(String procFile) {
		this.procFile = procFile;
		SNR = getSNR();
	}

	public void run() {

		try {
			//Main loop
			while (true) {
				float auxSNR = 0;
				//Get SNR media in three steps
				sleep(300);
				auxSNR = getSNR();
				sleep(300);
				auxSNR += getSNR();
				sleep(300);
				auxSNR += getSNR();
				SNR = auxSNR / 3;
				if (maxSNR<SNR)
					maxSNR=SNR;
				//Mensuring delay
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private float getSNR() {
		//Open file
		File file = new File(procFile);
		FileReader fileReader;
		BufferedReader in = null;
		try {
			fileReader = new FileReader(file);
			in = new BufferedReader(fileReader);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		//Read line		
		String status = null, inputLine;
		try {
			while ((inputLine = in.readLine()) != null) {
				if (inputLine != null)
					status = inputLine;
			}
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		//Parse line
		int i = 0;
		float quality = 0, signal = 0, noise = 0;
		StringTokenizer stok = new StringTokenizer(status);
		while (stok.hasMoreElements()) {
			String tok = (String) stok.nextElement();
			switch (i) {
				case 2 :
					quality = new Float(tok).floatValue();
					break;
				case 3 :
					signal = new Float(tok).floatValue();
					break;
				case 4 :
					noise = new Float(tok).floatValue();
					break;
			}
			i++;
		}

		//Return Signal Noise Ratio
		return (signal / noise);
	}

	public float getSNRValue() {
		return SNR;
	}

}