package cz.vutbr.feec.session.ping;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.Vector;

import org.apache.log4j.Logger;

import cz.vutbr.feec.session.gnp.LandmarkInfo;

/**
 * The Class LandmarkSession.
 */
public class LandmarkSession {

	private static Logger logger = Logger.getLogger(LandmarkSession.class
			.getName());

	private Vector<LandmarkInfo> lmsAdresses = new Vector<LandmarkInfo>();

	private double[] rttTable = null;

	/**
	 * The Constructor.
	 * 
	 * @param urlAddress the url address
	 * 
	 * @throws MalformedURLException the malformed URL exception
	 */
	public LandmarkSession(String urlAddress) throws MalformedURLException {
		URL url = new URL(urlAddress);
		logger.debug("initializiing from URL:" + urlAddress);
		init(url);
		
		logger.debug("Greating RTT vector");
		final int maxNumOfThreads = 5;
		final int pingCount = 3;
		rttTable =  RttVectorMeasurement.measureRttVector(lmsAdresses, maxNumOfThreads, pingCount);
	}

	/**
	 * Init the session from given url address.
	 * 
	 * @param url the url
	 */
	private void init(URL url) {
		String nextLine;
		URLConnection urlConn = null;
		InputStreamReader inStream = null;
		BufferedReader buff = null;
		try {
			// Create the URL obect that points
			// at the default file index.html
			urlConn = url.openConnection();
			inStream = new InputStreamReader(urlConn.getInputStream());
			buff = new BufferedReader(inStream);

			// Read and print the lines from index.html
			while (true) {
				nextLine = buff.readLine();
				if (nextLine != null) {
					if (!nextLine.startsWith("//") && !nextLine.startsWith("#")) {
						try {
							LandmarkInfo lm = parseLine(nextLine);
							lmsAdresses.add(lm);
						} catch (UnknownHostException e) {
							logger
									.warn("WARNING: Parsing of landmark address '"
											+ nextLine + "' failed");
						}
					}
				} else {
					break;
				}
			}
		} catch (IOException e1) {
			System.out.println("Can't read  from the Internet: "
					+ e1.toString());
			System.exit(-3);
		}
	}

	/**
	 * Parses the line of config.
	 * 
	 * @param nextLine the next line
	 * 
	 * @return the landmark info
	 * 
	 * @throws UnknownHostException the unknown host exception
	 */
	private LandmarkInfo parseLine(String nextLine) throws UnknownHostException {
		String[] str = nextLine.split(":");
		InetAddress addr = InetAddress.getByName(str[0]);
		LandmarkInfo lm = new LandmarkInfo(true, addr, -1);
		// parse Latitude and Longitude
		if (str.length == 4) {
			if (str[1].equals("K")) {
				try {
					float latitude = Float.parseFloat(str[2]);
					float longitude = Float.parseFloat(str[3]);

					lm.setLatitude(latitude);
					lm.setLongitude(longitude);
				} catch (Exception e) {
					logger
							.warn("WARNING: latitude & longitude parsing failed  '"
									+ nextLine + "' failed");
				}
			}
		}
		logger.debug("Landmark parsed: " + lm);
		return lm;
	}

	/**
	 * Vyvola u vsech ostatnich LM reinicializaci a prepocitani hodnot (jakoby
	 * nove spusten).
	 */
	public void invokeRecomputation() {
		// TODO poslat paket vsem a vyvolat tak reininicializaci
	}
}
