/*
 NAME
 	ctree-test.m - test program for CTree class
 VERSION
 	$Id$
 CHANGELOG
 	$Log$
 */

#include <coconut/ctree.h>
#include <coconut/cnode.h>
#include <coconut/cstring.h>
#include <coconut/cindtstream.h>

@interface CNodeWrapper : CNode
{
	char *	node_name ;
}

- initNodeWrapper: (const char *) name ;
- print: (id) strem ;

@end

@implementation CNodeWrapper

- initNodeWrapper: (const char *) name
{
	node_name = [CString duplicate: name] ;
	return [super init] ;
}

- (void) dealloc
{
	printf("releasing : %s\n", node_name) ;
	[CString free: node_name] ;
	[super dealloc] ;
}

- print: (id) stream
{
	[stream putFormat: "(node %s)", node_name] ;
	return nil ;
}

@end

void printTree(id <PTree> tree, id <PIndentStream> stream)
{
	id <PNode> 	node ;

	fflush(stdout) ;

	[stream putFormat: "count: %u\n", [tree count]] ;

	[stream putPtr: "root:"] ;
	node = [tree rootNode] ;
	[stream putPtr: "root node: "] ;
	if(node)
		[node print: stream] ;
	else
		[stream putPtr: "nil"] ;
	[stream putChar: '\n'] ;

	[stream putPtr: "current:"] ;
	node = [tree currentNode] ;
	if(node)
		[node print: stream] ;
	else
		[stream putPtr: "nil"] ;
	[stream putChar: '\n'] ;

	[stream putPtr: "list:\n----\n"] ;
	[tree print: stream] ;
	[stream putPtr: "----\n"] ;

	[stream flush] ;
}

int main()
{
	id <PTree>		tree1 ;
	id <PIndentStream>	stream ;
	CNodeWrapper *		node1 ;
	CNodeWrapper *		node2 ;
	CNodeWrapper *		node3 ;
	CNodeWrapper *		node4 ;

	printf("*** test program for CTree class\n");
	tree1 = [[CTree alloc] init] ;
	stream = [[CIndtStream alloc] init] ;
	node1 = [[CNodeWrapper alloc] initNodeWrapper: "1"] ;
	node2 = [[CNodeWrapper alloc] initNodeWrapper: "2"] ;
	node3 = [[CNodeWrapper alloc] initNodeWrapper: "3"] ;
	node4 = [[CNodeWrapper alloc] initNodeWrapper: "4"] ;

	printf("initial state:\n") ;
	printTree(tree1, stream) ;

	printf("add first node:\n") ;
	[tree1 addSibling: node1] ; [node1 release] ;
	printTree(tree1, stream) ;

	printf("insert second node:\n") ;
	[tree1 insertSibling: node2] ; [node2 release] ;
	printTree(tree1, stream) ;

	printf("append and prepend children:\n") ;
	[tree1 prependChild: node3] ; [node3 release] ;
	printTree(tree1, stream) ;
	[tree1 appendChild: node4] ; [node4 release] ;
	printTree(tree1, stream) ;

	printf("move to last child and move to parent:\n") ;
	printf("can i return the same place?\n") ;
	printTree(tree1, stream) ;

	printf("remove the current node:\n") ;
	[tree1 removeCurrentNode] ;
	printTree(tree1, stream) ;

	printf("end of the program:\n");
	[stream flush] ;

	[tree1 release] ;
	[stream release] ;
	printf("bye.\n") ;
	return 0 ;
}

