/**
 * RecipeParser.java
 *
 *
 * @author 
 * @version 1.00 2007/11/22
 */


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


public class RecipeParser { 

    final private String xmlStartTag = "<xml>";
    final private String xmlEndTag = "</xml>";
	private RecipeBook recipeBook;
	
	public RecipeBook getRecipes(){return recipeBook;}
   
    public RecipeParser(String fileName) throws FileOpeningException {
		try {
			RecipeBook recipes = new RecipeBook();
			Recipe currentRecipe = null;
			StringBuffer text = new StringBuffer();
			String activeTag = "";
			String input;
			int numberOfStartRecipes = 0;
			int numberOfEndRecipes = 0;
			BufferedReader xmlInputFile = new BufferedReader(new FileReader(fileName));
			
			while((input = xmlInputFile.readLine()) != null) { 
				String s = input.trim();
				
				if(s.startsWith(xmlStartTag)){
					//System.out.println("START PARSING");
				}
				else if(s.startsWith(xmlEndTag)){
					//System.out.println("END PARSING");
				}
				else if (s.startsWith(Recipe.getStartTag())) {
					currentRecipe = new Recipe();
					text = new StringBuffer();
					numberOfStartRecipes++;
				}
				else if (s.startsWith(Recipe.getEndTag())) {
					recipes.add(currentRecipe);
					currentRecipe = null;
					numberOfEndRecipes++;
				}
				else if (Recipe.isXMLStartTag(s)) {
					activeTag = s;
					text = new StringBuffer();
				}
				else if (Recipe.isXMLEndTag(s)) {
					if(currentRecipe != null) currentRecipe.setXMLField(activeTag, text);
					text = null;
				}
				else
					if(text != null) text.append(s).append("\n");

			}
			xmlInputFile.close();
			
			recipeBook = recipes;
			 
		} catch (FileNotFoundException e) {
			throw new FileOpeningException("Error: Cannot open file for reading.");
		} catch (EOFException e) {
			throw new FileOpeningException("Error: EOF encountered, file may be corrupted.");
		} catch (IOException e) {
			throw new FileOpeningException("Error: Cannot read from file.");
		}

	}
	
}