// WordList.cpp
// linked list of words

#include "wordlist.h"
#include "htmlwriter.h"
using namespace std;

WordList::WordList( string name ) {
	assignName(name);
	Next = NULL;
}


WordList *WordList::addGet( string name ) {
	if (getName().empty()) {
		//cout << "\nFirst word for this letter - " << name;
		assignName(name);
		return this;
	}
	else if (value == name) {
		//cout << "found dupe\n";
		return this;
	}
	else { if (name < getName()) {
			//cout << "\n|" << name << "| < |" << value << "| adding at front"; 
			WordList *temp = new WordList(getName());
			temp->assignNext(*Next);
			assignNext(*temp);
			temp->URLList = this->URLList;
			temp->URLDescriptions = this->URLDescriptions;
			StringList newEmpty;
			this->URLList = newEmpty;
			this->URLDescriptions = newEmpty;
			this->assignName(name);				 		
			return this;
	
		}
		else if (getNext() == NULL) {
				//cout << "\nAdding " << name << ". . .";
				Next = new WordList(name);
				return getNext();
			}
			else if (name >= getNext()->getName()) {
					//cout << "\n|" << name << "| != |" << value << "|	Calling next . . .";
					return getNext()->addGet(name);
				}
				else {
					//cout << "\n|" << name << "| >= |" << value << "| and < |" << getNext()->getName() << "| ... adding";
					WordList *temp = new WordList(name);
					temp->assignNext(*Next);
					assignNext(*temp);
					return getNext();
				}
	}
}


int WordList::addURL( string URL, string description ) {
		if (URLList.add(URL)) {
			URLDescriptions.addNoRestrict(description);
		}
}

string WordList::getName() {
		return value;
}

WordList *WordList::getNext() {
		return Next;
}

int WordList::assignName( string name ) {
		value = name;
}

void WordList::print( string outputDIR) {
		HTMLWriter wordPage;
		wordPage.open(outputDIR+getName()+".html");
		wordPage.header("Results for '"+getName()+"'");
		StringList *tempURLList = &URLList;
		StringList *tempURLDescriptions = &URLDescriptions;
		while ((tempURLList != NULL) && (tempURLDescriptions != NULL)) {
			wordPage.link(tempURLList->getName(),tempURLList->getName());
			wordPage.bodyText("<blockquote> - "+tempURLDescriptions->getName() + " </blockquote>");
			tempURLDescriptions = tempURLDescriptions->getNext();
			tempURLList = tempURLList->getNext();
		}
		wordPage.footer();
}

void WordList::rprint( string outputDIR) {
		print(outputDIR);
		if (getNext() != NULL)
			getNext()->rprint(outputDIR);
}

int WordList::assignNext( WordList &newNext) {
		Next = &newNext;
		return 1;
}

WordList::~WordList() {
		if (getNext() != NULL) { delete Next; }
}

void WordList::testList() {
		cout << "|" << getName() << "| :	";
		URLList.testList();
		cout << "\n";
		if (getNext() != NULL) getNext()->testList();
}
