/**
 * @(#)RecipeProgram.java
 *
 *
 * @author 
 * @version 1.00 2007/11/26
 */

import java.util.*;
import java.io.*;

public class RecipeProgram {
	
	private static ArrayList<Recipe> recipes;
	private static String spiceSelected = "any";
	private static String ratingSelected = "any";
	private static String fileName;
	final private static String xmlStartTag = "<xml>";
    final private static String xmlEndTag = "</xml>";
	
    public static void main(String args[])/* throws FileOpeningException*/{
		Scanner userInput = new Scanner(System.in); //create stream for reading keyboard
		String userInputString;
		int userSelection = 0;
    	
		System.out.print("Welcome to Spice of Life Browser!\nEnter name of file (ex. aLaCarteData.txt): ");
		fileName = userInput.nextLine();
		
		System.out.println("Working... ");
		//RecipeParser parser = new RecipeParser(fileName);
		RecipeParser parser = null;
		try{
			parser = new RecipeParser(fileName);
		}
		catch(FileOpeningException e){
			System.out.println(e.toString());
            System.exit(-1);
		}
		System.out.println("... " + parser.getRecipes().size() + " recipes loaded.");
		recipes = parser.getRecipes();
		
		while(userSelection != 8){
			System.out.println("\n\nMenu Options:");
			System.out.println("\t1. Find Contributor");
			System.out.println("\t2. Select Spice");
			System.out.println("\t3. Select Rating");
			System.out.println("\t4. List Recipe Names");
			System.out.println("\t5. Display Recipe");
			System.out.println("\t6. Enter New Recipe");
			System.out.println("\t7. Save");
			System.out.println("\t8. Exit");
			
			System.out.print("Enter selection (ex. 1): ");
			userSelection = userInput.nextInt();
			System.out.println("");
			
			switch (userSelection){
				case 1:
					findContributor();
					break;
				case 2:
					selectSpice();
					break;
				case 3:
					selectRating();
					break;
				case 4:
					listRecipeNames();
					break;
				case 5:
					displayRecipe();
					break;
				case 6:
					enterNewRecipe();
					break;
				case 7:
					save();
					break;
				case 8:
					saveAndExit();
				default:
			}
		}
		
		//String prompt = "Enter recipe number 1..." + parser.getRecipes().size() + ", student number or CR to quit";
		//System.out.println(prompt);
			
		//System.out.println("number of recipes = " + parser.getRecipes().size() );
			
		/*while((userInputString = userInput.nextLine()).length() > 0 ) {
			try {
				int recipeNumber = Integer.parseInt(userInputString);
				if((recipeNumber > 0) && (recipeNumber <= parser.getRecipes().size() )) {
					Recipe aRecipe = parser.getRecipes().get(recipeNumber - 1);
					aRecipe.printOn(System.out);
				}
				else{
					System.out.println("RECIPE NUMBER IS OUT OF RANGE");
				}
			}
			catch (NumberFormatException e) {
				System.out.println("INVALID RECIPE NUMBER FORMAT");
			}
				
			System.out.println(prompt);  
		}*/
    }
    
    private static void findContributor(){
    	String studentNum = "";
    	boolean isValidNumber = false;
    	while(isValidNumber==false){
    		isValidNumber = true;
    		System.out.print("Enter student number (6 digits): ");
    		studentNum = new Scanner(System.in).nextLine();
    		if(studentNum.length()!=6){
    			System.out.println("Sorry, that isn't a valid student number.");
    			isValidNumber = false;
    		}
    		else{
    			try{
    				int test = Integer.parseInt(studentNum);
    			}
    			catch(NumberFormatException e){
    				System.out.println("Sorry, that isn't a valid student number.");
    				isValidNumber = false;
    			}
    		}
    	}
    	boolean isContributor = false;
    	
    	for(int i=0; i<recipes.size(); i++){
    		if (recipes.get(i).getNumber().contains(studentNum)){
    			System.out.println((i+1) + ". " + recipes.get(i).getName());
    			isContributor = true;
    		}
    	}
    	if (!isContributor){
    		System.out.println("Sorry, no such contributor exists.");
    	}
    	System.out.println("\nPress enter to return to menu.");
    	String returnToMenu = new Scanner(System.in).nextLine();
    }
    
    private static void selectSpice(){
    	System.out.print("Enter spice: ");
    	spiceSelected = new Scanner(System.in).nextLine();
    	System.out.println("\nPress enter to return to menu.");
    	String returnToMenu = new Scanner(System.in).nextLine();
    }
    
    private static void selectRating(){
    	System.out.print("Enter rating: ");
    	ratingSelected = new Scanner(System.in).nextLine();
    	System.out.println("\nPress enter to return to menu.");
    	String returnToMenu = new Scanner(System.in).nextLine();
    }
    
    private static void listRecipeNames(){
    	int count = 0;
    	for (int i=0; i<recipes.size(); i++){
    		if((ratingSelected.toLowerCase().equals("any") || 
    			ratingSelected.toLowerCase().equals(recipes.get(i).getRating().toLowerCase())) &&
    			(spiceSelected.toLowerCase().equals("any") || 
    			recipes.get(i).getSpice().toLowerCase().contains(spiceSelected.toLowerCase()))){
    				System.out.println((i+1) + ". " + recipes.get(i).getName().trim());
    				count++;
    				if (count%21 == 0){
    					System.out.println("\nPress enter for more...");
    					String more = new Scanner(System.in).nextLine();
    				}
    				for(int j=0; j<recipes.get(i).getName().trim().length(); j++){
    					if (recipes.get(i).getName().trim().charAt(j) == '\n'){
    						count++;
    						if (count%21 == 0){
    							System.out.println("\nPress enter for more...");
    							String more = new Scanner(System.in).nextLine();
    						}	
    					}
    				}
    		}
    	}
    	System.out.println("\nPress enter to return to menu.");
    	String returnToMenu = new Scanner(System.in).nextLine();
    }
    
    private static void displayRecipe(){
    	System.out.print("Enter a recipe number(starting at 1): ");
    	int recipeNumber = new Scanner(System.in).nextInt();
    	recipes.get(recipeNumber-1).printOn(System.out);
    	
    	System.out.println("\nPress enter to return to menu.");
    	String returnToMenu = new Scanner(System.in).nextLine();
    }
    
    private static void enterNewRecipe(){
    	Scanner input = new Scanner(System.in);
    	String str;
    	String aName="", aRating="", aContributor="", someSpices="", aSource="", aCategory="", aDescription="";
    	String someIngredients="", someDirections="";
    	
    	//System.out.println("When finished each entry, type * to end.");
    	
    	System.out.print("Enter name of recipe (1 line only): ");
    	aName = input.nextLine();
    	/*while(!(str = input.nextLine()).equals("*")){
    		aName = aName + str;
    	}*/
    	
    	System.out.print("\nEnter a rating (1 line only): ");
    	aRating = input.nextLine();
    	/*while(!(str = input.nextLine()).equals("*")){
    		aRating = aRating + str;
    	}*/
    	
    	System.out.print("\nEnter your student number (6 digits): ");
    	aContributor = input.nextLine();
    	/*while(!(str = input.nextLine()).equals("*")){
    		aContributor = aContributor + str;
    	}*/
    	
    	System.out.print("\nEnter the main spices used (enter * as last line): ");
    	while(!(str = input.nextLine()).equals("*")){
    		someSpices = someSpices + str;
    	}
    	
    	System.out.print("\nEnter the source of the recipe (1 line only): ");
    	aSource = input.nextLine();
    	/*while(!(str = input.nextLine()).equals("*")){
    		aSource = aSource + str;
    	}*/
    	
    	System.out.print("\nEnter the category of the dish (1 line only): ");
    	aCategory = input.nextLine();
    	/*while(!(str = input.nextLine()).equals("*")){
    		aCategory = aCategory + str;
    	}*/
    	
    	System.out.print("\nEnter a description (enter * as last line): ");
    	while(!(str = input.nextLine()).equals("*")){
    		aDescription = aDescription + str;
    	}
    	
    	System.out.print("\nEnter the ingredients (enter * as last line): ");
    	while(!(str = input.nextLine()).equals("*")){
    		someIngredients = someIngredients + str;
    	}
    	
    	System.out.print("\nEnter the directions (enter * as last line): ");
    	while(!(str = input.nextLine()).equals("*")){
    		someDirections = someDirections + str;
    	}
    	recipes.add(new Recipe(aName, aRating, aContributor, someSpices, aSource, aCategory, aDescription,
    		someIngredients, someDirections));
    	System.out.println("\nPress enter to return to menu.");
    	String returnToMenu = new Scanner(System.in).nextLine();
    }
    
    private static void save(){
    	System.out.print("Would you like to overwrite the old file? (y/n): ");
    	String newFileName;
    	
    	char userChoice = new Scanner(System.in).nextLine().charAt(0);
    	if (userChoice != 'y' && userChoice != 'Y'){
    		System.out.print("Enter name of new file: ");
    		newFileName = new Scanner(System.in).nextLine();
    	}
    	else{
    		newFileName = fileName;
    	}
    	try{
    		PrintWriter xmlResultFile = new PrintWriter(new FileWriter(newFileName));
    		xmlResultFile.println(xmlStartTag);
			
			for(Recipe aRecipe : recipes) 
				aRecipe.printXMLOn("   ", xmlResultFile); 
			
			xmlResultFile.println(xmlEndTag);
			
			xmlResultFile.close();
			System.out.println("Saving file...");
    	}
    	catch(IOException e){
    	}
    	System.out.println("\nPress enter to return to menu.");
    	String returnToMenu = new Scanner(System.in).nextLine();
    }
    private static void saveAndExit(){
    	try{
    		PrintWriter xmlResultFile = new PrintWriter(new FileWriter(fileName));
    		xmlResultFile.println(xmlStartTag);
			
			for(Recipe aRecipe : recipes) 
				aRecipe.printXMLOn("   ", xmlResultFile); 
			
			xmlResultFile.println(xmlEndTag);
			
			xmlResultFile.close();
			System.out.println("Saving file...");
    	}
    	catch(IOException e){
    	}
    }
}