// YahooNode.cpp: implementation of the YahooNode class.
//
//////////////////////////////////////////////////////////////////////

#include "YahooNode.h"

istream & operator >>(istream & is, YahooNode &n)
{
	const string topicBegin("<Topic r:id=\"Top/Computers/");
	const string dirEnd("\">");
	const string topicEnd("</Topic>");
	const string urlBegin("<link r:resource=\"");
	const string urlEnd("\"/>");
	string line;

	string::size_type start;
	string::size_type end;

	n.title = ""; //if we find nothing, the title will be ""

	while(getline (is, line)) {
		start = line.find(topicBegin);
		if (start != string::npos){
			start += topicBegin.size();
			end = line.find(dirEnd);
			n.title = line.substr(start, end-start);

			while ((start = n.title.find("/")) != string::npos){
				n.title.replace(start,1, "-");
			}
		}
		start = line.find(urlBegin);
		if (start != string::npos) {
			start += urlBegin.size();
			end = line.find(urlEnd);
			string url = line.substr(start, end-start);
			n.urls.push_back(url);
		}
		start = line.find(topicEnd);
		if (start != string::npos)
			break;
	};
	return is;
}



// Determine is n is our child based on the titles
//
//title Computer_Science/People/A
// n.title Computer_Science/People
bool YahooNode::childOf(const YahooNode &n)
{
	string::size_type pos;
	pos = title.find(n.title); //is his title is part of mine?
	if (pos == string::npos) //no
		return false;
	else //yes
		return true;
}


void YahooNode::addChild(YahooNode *n)
{
//	cout << "Adding child " << n->title << endl;
	n->nextSibling = 0; //just to make sure this is the last child.

	if (firstChild == 0){
		firstChild = n;
	}
	else {
		YahooNode *c;
		for (c = firstChild; c->nextSibling != 0; c = c->nextSibling)
		{};
		c->nextSibling = n;
	}
}



void YahooNode::printAsHTML(map<string, URL> & m)
{
	string filename = title + ".html";
	ofstream fout(filename.c_str());
	if (fout == 0) {
		cerr << "Could not open " << filename << endl;
		return;
	}
	fout << "<html><head><title>PS8:" << title << "</title></head><body>" << endl
		<< "<center><h1>" << title << "</h1></center>" << endl;

	fout << "<hr><ul>" << endl;
	for (YahooNode * c = firstChild; c != 0; c= c->nextSibling){
		string fname = c->title + ".html";
		fout << "<li><a href=\"" << fname << "\"><b>" << c->title << "</b></a>" << endl;
	};
	fout << "</ul><hr>" << endl;

	fout << "<ul>" << endl;
	vector<string>::iterator i;
	for (i = urls.begin(); i!= urls.end(); ++i){
//		fout << "<li><a href=\"" << *i << "\">" << *i << "</a>" << endl;
		string & r = *i;
		URL u = m[r];
		fout << "<li>" << u << endl;
	}
	fout << "</ul>" << endl;
	fout << "</html>" << endl;
	if (firstChild != 0)
		firstChild->printAsHTML(m);
	if (nextSibling != 0)
		nextSibling->printAsHTML(m);
}