import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
/**
 * \brief Trida slouzici k nacitani souboru z knihovny TSPLib
 * @author nemec
 *
 */
public class TspParser {

	private double[][] distances;
	private int size;
	private ArrayList<CitiesTSP> cities = new ArrayList<CitiesTSP>();
	/**
	 * Konstruktor, ktery zaroven nacita potrebna data, funguje pouze s daty typu EUC_2D.
	 * @param path Cesta ke vstupnimu souboru
	 * @throws IOException
	 */
	public TspParser(String path) throws IOException{
		
		Scanner scanner = new Scanner(new FileReader(path));
		
		
		int x,y,number;
		
		String temp;
		int size=0;
		
		while(scanner.hasNext()){
			temp = scanner.next();
			System.out.println(temp);
			if(temp.equals("DIMENSION:")){
				size = Integer.parseInt(scanner.next());
				System.out.println(size);
			}
			//System.out.println(bla);
			
			if(temp.equals("NODE_COORD_SECTION")){
				while(scanner.hasNext()){
					temp = scanner.next();
					number = Integer.parseInt(temp);
					temp = scanner.next();
					x = Integer.parseInt(temp);
					temp = scanner.next();
					y = Integer.parseInt(temp);
					
					cities.add(new CitiesTSP(x, y));
					
					//System.out.println(size);
					System.out.println("Added city: " + number + " with coordinates x: " + x + " and y: " + y);
					
					if(number == size)
						break;
				}
			}
			
		}
		
		scanner.close();
		this.size = size;
		this.distances = calculateDistances();
		
	}
	
	private double[][] calculateDistances(){
		
		double temp[][] = new double[this.size][this.size];
		
		for(int i=0; i<this.size; i++){
			for(int j=0; j<this.size; j++)
				temp[i][j] = getDistance(this.cities.get(i), this.cities.get(j));
		}
		
		return temp;
	}
	/**
	 * Funkce, ktera vraci vzadelenost mezi dvema mesty
	 * @param city1 Mesto1
	 * @param city2	Mesto2
	 * @return Vysledna vzdalenost
	 */
	private double getDistance(CitiesTSP city1, CitiesTSP city2){
		//distance = (int) Math.sqrt(Math.pow((city2.GetX()-city1.GetX()), 2) + Math.pow(city2.GetY() - city1.GetY(), 2));
		double distance = Math.sqrt(Math.pow((city1.getX()-city2.getX()), 2) + Math.pow((city1.getY() - city2.getY()), 2));
		
		return distance;
		
	}
	/**
	 * Vraci tabulku obsahujici vzdalenosti mezi vsemi mesty z nacteneho souboru
	 * @return Tabulka vzdalenosti
	 */
	public double[][] getDistances(){
		return this.distances;
	}
	/**
	 * Funkce, ktera vraci pocet mest
	 * @return Pocet mest
	 */
	public int getSize(){
		return this.size;
	}
	
}
