package project_3;
import java.io.File;
import java.util.Scanner;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.stage.Stage;

public class Main extends Application{
	static Tree<Country> tree = new Tree<>();
	static TreeNode<Country> root;
	static LinkedList<Country> countryList = new LinkedList<>();
	static HashTable table;

	
	//Read Data
	public static String loadData(){
		File f;
		Scanner in;
		String s="";
		try {
			f = new File("cc.txt");
			in = new Scanner(f);

			while(in.hasNext()){
				s+=in.nextLine()+"#";
			}
		} 
		catch (Exception e) {
			System.exit(0);
		}
		return s;
	}
	
	//Traverse the tree and add the cities to hash table
	public static void TreeData(TreeNode<Country> root){
		if(root==null)
			return;

		TreeData(root.left);

		for (int i = 0; i < root.data.getList().getSize(); i++) {
			table.insert(root.data.getList().getIndexData(i).getName(),root.data.getList().getIndexData(i));
		}

		TreeData(root.right);
	}

	//Find specific city in a country
	private static boolean cityFound(Country c,City city) {
		for (int i = 0; i < c.getList().getSize(); i++) {
			if(c.getList().getIndexData(i).getName().equalsIgnoreCase(city.getName()))
				return true;
		}
		return false;
	}

	public static void main(String[] args) {
		String s = loadData();

		String []arr = s.split("[#]");
		String [] splitted;
		Country c;
		City city;

		//Split the reading file and add country to tree and cities in their countries
		for (int i = 0; i < arr.length; i++) {
			splitted = arr[i].split("[*]");

			try{
				c = new Country(splitted[2]);
				TreeNode<Country> found = tree.find(root,c);
				city = new City(Integer.parseInt(splitted[0]), splitted[1], Double.parseDouble(splitted[3]));

				//If country does not exist in the tree then just add it to tree and add its city
				if(found==null){
					
					c.addCity(city);

					root = tree.insert(root, c);
				}
				else{
					//If the country found and the city does not found in this country then add this city
					if(!cityFound(found.data,city))
						found.data.addCity(city);
				}

			}
			catch (Exception e) {

			}
		}

		//Read the tree in a linkedList print it in GUI
		tree.readData(root, countryList);

		//Make a hashTable and pass the number of countries to initialize its size
		table = new HashTable(tree.countNodes(root));

		TreeData(root);
		
		
		launch(args);


	}


	@Override
	public void start(Stage primaryStage) throws Exception {

		new MainScene(countryList, table,root,tree.countNodes(root)).show();
	}
}
