package cz.vutbr.feec.session.ping;

import java.net.InetAddress;
import java.util.Vector;

import org.apache.log4j.Logger;

/**
 * The Class RttTable.
 */
public class RttVectorMeasurement {
	private static Logger logger = Logger.getLogger(RttVectorMeasurement.class.getName());

	/**
	 * Measures an rtt vector.
	 * 
	 * @param address
	 *            the IP address
	 * @param pingCount
	 *            the number of repeats for pinging each address
	 * @param maxNumOfThreads
	 *            the max num of threads running consequently
	 * 
	 * @return the double[]
	 */
	public static double[] measureRttVector(InetAddress address[],
			int maxNumOfThreads, int pingCount) {
		
		ThreadPool threadPool = new ThreadPool(maxNumOfThreads);
		Vector<RttMeasurement> pool = new Vector<RttMeasurement>();
		
		for (int i = 0; i < address.length; i++) {
			int id = 2000 + i;
			RttMeasurement task = new RttMeasurement(address[i], id, pingCount);
			threadPool.runTask(task);
			pool.add(task);
		}
		logger.debug("Synchronizing threads");
		threadPool.join();
		double[] res = new double[address.length];
		for (int i = 0; i < pool.size(); ++i) {
			logger.debug("HOST: " + address[i] + ", MINIMAL RTT: "
					+ pool.get(i).getResult());
			res[i] = pool.get(i).getResult();
		}
		return res;
	}
	/**
	 * Measures the rtt distances to adresses.
	 * 
	 * @param address
	 *            the IP address
	 * @param pingCount
	 *            the number of repeats for pinging each address
	 * @param maxNumOfThreads
	 *            the max num of threads running consequently
	 * 
	 * @return the double[]
	 */
	public static double[] measureRttVector(Vector<? extends IAddress> address,
			int maxNumOfThreads, int pingCount) {
		ThreadPool threadPool = new ThreadPool(maxNumOfThreads);
		Vector<RttMeasurement> pool = new Vector<RttMeasurement>();
		for (int i = 0; i < address.size(); ++i) {
			int id = 2000 + i;
			RttMeasurement task = new RttMeasurement(address.get(i).getAddress(), id, pingCount);
			threadPool.runTask(task);
			pool.add(task);
		}
		logger.debug("Synchronizing threads");
		threadPool.join();
		double[] res = new double[address.size()];
		for (int i = 0; i < pool.size(); ++i) {
			logger.debug("HOST: " + address.get(i) + ", MINIMAL RTT: "
					+ pool.get(i).getResult());
			res[i] = pool.get(i).getResult();
		}
		return res;
	}

}
