// Browser.cpp
// manages browsing

#include "htmlwriter.h"
#include "browser.h"

// Constructor
Browser::Browser( string stopWord) : parser( database , stopWord) {
//		cout << "Browser Constructor Called";
}

// Reads page until parser object no longer returns a new link
int Browser::readPages( string URL, string domain){
		parser.setDomain(domain);
		string nextURL = URL;
		int readError = 0;
		//cout << "\nNow starting readPage loop -- reading " << nextURL << "\n";
		while ((readError != -1) && ( !nextURL.empty())) {
			readError = readPage( nextURL );
			cout << "\nreadError :" << readError << "\n";
			//database.testWord();
			//cin.get();
			nextURL = parser.nextLink();
			//cout << "\nRead Succesful -- now reading " << nextURL << "\n";
		}
		//cout << "\nout of read loop\n";
		//cin.get();
		return readError;
}

// Routine for reading an individual page
int Browser::readPage( string URL ) {
		//cout << "\nOpening Page ...";
		//cin.get();
		parser.open(URL);
		//cout << "\nGetting Description ...";
		//cin.get();
		string description = parser.getDescription();
		//cout << "\n" << description << "\nGetting next string ...";
		//cin.get();
		string input = parser.nextString();
		//cout << "\ngot next string:	" << input;
		//cin.get();
		while ((!parser.getReadError()) && (!input.empty())) {
			database.tally( input, URL, description );
			//cout << "DataBase update on " << input << ":\n";
			//database.testWord();
			//cin.get();
			input = parser.nextString();
		}
		//cout << "\ndocument read, current database:\n";
		//database.testWord();
		//cin.get();
		parser.close();
		return parser.getReadError();
		
}

// Calls the print methods on all data
void Browser::writePages( string outputDIR) {
		database.print(outputDIR);
}

