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

#include "URL.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

URL::URL() : url(""), title(""), description("") //set the default port
{

}

URL::~URL()
{
}

URL::URL(string & u) : url(u), title(""), description("")
{
}

URL::URL(string &u, string &t, string &d) : url(u), title(t), description(d)
{
}

//copy constructor, only does memberwise copy so its not 
// really needed.
URL::URL(const URL &u) : url(u.url), title(u.title), description(u.description)
{
}


ostream & operator<<(ostream & os, const URL & u){
	os << "<a href=\"" << u.url << "\">" << u.title 
		<< "</a>";
	if (u.description != "")
		os << "- "<< u.description;
	os << "<br>";
	return os;
}


//just for fun..but useful for PS8
int URL::operator ==(const URL &u) const
{
	return (url == u.url);
	
}

//Given istream, it gets input from it until it finds
// the next <ExternalPage> block. It reads this block
// into u.
//It assumes that we are OUTSIDE and ExternalPage block
istream & operator >>(istream &is, URL &u)
{
	//some const values this operator needs.
	//You should ALWAYS use const variables rather than explicitly
	//  using the actual string (aka: "magic strings"). This way its
	//  easy to modify the program. These values could also be global
	//  variables if they are needed by other functions.
	const string urlBegin = "<ExternalPage about=\"";
	const string urlEnd = "\">";
	const string pageEnd = "</ExternalPage>"; //when we find this, we return
	const string titleBegin = "<d:Title>";
	const string titleEnd = "</d:Title>";
	const string descBegin = "<d:Description>";
	const string descEnd = "</d:Description>";

	//the variables
	string::size_type start;
	string::size_type end;
	string line;
	u.url = "";
	u.title = "";
	u.description = "";
	while (getline (is, line)) { //continue reading until EOF 
		start = line.find(urlBegin); //or until we break out
		if (start != string::npos) {
			start += urlBegin.size();
			end = line.find(urlEnd);
			u.url = line.substr(start, end-start);
			continue;
		}
		start = line.find(titleBegin);
		if (start != string::npos){
			start+= titleBegin.size();
			end = line.find(titleEnd);
			u.title = line.substr(start, end-start);
		continue;
		}
		start = line.find(descBegin);
		if (start != string::npos){
		start+=descBegin.size();
			end = line.find(descEnd);
			u.description = line.substr(start, end-start);
		}
		start = line.find(pageEnd);
		if (start != string::npos)
		break; //found the next end of page, so its time to break out
	}
	return is;
}


int URL::operator<(const URL &u) const{
	return url < u.url;
}

//bool URL::sortByTitle(const URL & b)
//{
//	return title < b.title;
//}