//File Parser.h - contains Parser class
//Code has been adapted from previous Java assignment

//Make sure the file hasn't been included already
#ifndef _parser_h
#define _parser_h

#include <string>
#include <list>
#include <cstdio>
#include <fstream>
#include "Recipe.h"

//Definition of Parser class
class Parser{
public:
	list<Recipe> getRecipes(){ return recipeList;}

	Parser(string fileName){
		xmlStartTag = "<xml>";
		xmlEndTag = "</xml>";
		list<Recipe> recipes;					//List of parsed recipes
		Recipe * currentRecipe;					//Current recipe being parsed
		Recipe blank;							//Used to get the tags
		string * text;							//For collecting current info
		string activeTag = "";					//Current XML tag being parsed
		//char * input;							//Current input line from data file
		char input[1024];
		int numberOfStartRecipes = 0;			//Number of <recipe> tags read
		int numberOfEndRecipes = 0;				//Number of </recipe> tags  read

		ifstream fin(fileName.c_str(), ios::in); //Open the file for reading
		
		//Parse recipes, if the file was opened correctly
		if(fin){
			while(fin >> input) {
				string s = Trim(input);
				//System.out.println(s);
				
				if(StartsWith(s, xmlStartTag)){
					cout << "START PARSING" << endl;
				}
				else if(StartsWith(s, xmlEndTag)){
					cout << "END PARSING" << endl;
				}
				else if (StartsWith(s, blank.getStartTag())) {
					//start a new recipe
					currentRecipe = new Recipe();
					text = new string();
					numberOfStartRecipes++;
				}
				else if (StartsWith(s, blank.getEndTag())) {
					//end the current recipe
					recipes.push_front(*currentRecipe);
					delete currentRecipe;
					currentRecipe = NULL; //reset current recipe
					//delete text;
					//text = NULL;
					numberOfEndRecipes++;
				}
				else if (blank.isXMLStartTag(s)) {
					//change the field whose description is being collected
					activeTag = s;
					text = new string();
				}
				else if (blank.isXMLEndTag(s)) {
					//set the field of whose description is being collected
					if(currentRecipe != NULL)
						currentRecipe->setXMLField(activeTag, *text);
					delete text;
					text = NULL;
				}
				else
					//append text to current recipe field being collected
					if(text != NULL)
						text->append(s).append("\n");

			}
		}
		//Inform the user if the file did not open correctly
		else{
			cout << "ERROR: could not open file " << fileName << endl;
		}
		fin.close(); //close the input file
		recipeList = recipes;
	}
private:
	string xmlStartTag;
    string xmlEndTag;
	list<Recipe> recipeList;
};

//Overloaded insertion operator for the Parser class
/*ostream & operator<<(ostream & ostr, const Parser & p) {
     p.printOn(ostr);
     return ostr;
}*/
#endif
//End of Parser.h