/*******************************************************************************
 *	BHtml		HTML Generation classes
 *			T.Barnaby,	BEAM Ltd,	2006-09-03
 *******************************************************************************
 */
#include <BHtml.h>

BHtml::BHtml(BString tag, BString args, BString text){
	this->tag = tag;
	this->args = args;
	if(text != "")
		this->appendText(text);
}

BHtml::~BHtml(){
}

BHtml* BHtml::append(BHtml node){
	nodes.append(node);
	return &nodes.rear();
}

BHtml* BHtml::append(BString tag, BString args, BString text){
	nodes.append(BHtml(tag, args, text));
	return &nodes.rear();	
}

BHtml* BHtml::appendText(BString text){
	nodes.append(BHtml("", text));
	return &nodes.rear();
}

BString		BHtml::render(){
	BString	str;
	BIter	i;
	
	if(tag == ""){
		str = str + args;
	}
	else {
		if(args != ""){
			str = str + "<" + tag + " " + args + ">";
		}
		else {
			str = str + "<" + tag + ">";
		}
		
		if((tag == "html") || (tag == "body") || (tag == "table")){
			str = str + "\n";
		}

		for(nodes.start(i); !nodes.isEnd(i); nodes.next(i)){
			str = str + nodes[i].render();
		}
		
		str = str + "</" + tag + ">";
		
		if((tag == "html") || (tag == "body") || (tag == "tr") || (tag == "table")){
			str = str + "\n";
		}
	}
	
	return str;
}

#ifdef ZAP	
int main(int argc, char **argv){
	BHtml	b("body");
	BHtml*	t;
	BHtml*	r;
	
	b.append(BHtml("h1", "", "Hi There"));
	t = b.append(BHtml("table"));
	r = t->append(BHtml("tr"));
	r->append(BHtml("td", "", "Col0"));
	r->append(BHtml("td", "", "Col1"));
	r->append(BHtml("td", "", "Col2"));
	r->append("td", "", "Col3");
	r = t->append(BHtml("tr"));
	r->append(BHtml("td", "", "Col0"));
	r->append(BHtml("td", "", "Col1"));
	r->append(BHtml("td", "", "Col2"));
	r->append("td", "", "Col3");
	
	printf("%s\n", b.render().retStr());
	
	return 0;
}
#endif
