package prolog.implementation;

import java.io.*;
import java.util.*;
import prolog.model.*;
import prolog.util.*;

/**
 * <p>Title: NodeStatement</p>
 * <p>Descrpition: A class abstract base class prepresenting a statement
 * with more than one child statements </p>
 */
public abstract class NodeStatement
	extends AbstractStatement
	implements IStatement
{
	/**
	 * stores the child statements
	 */
	protected List childs = new ArrayList(0);

	/**
	 * constructor
	 * @param name
	 */
	public NodeStatement( int name )
	{
		super( name );
	}

	/**
	 * adds a child statement to this node
	 * @param s is the statement to be added
	 */
	public void addStatement( IStatement s )
	{
		if( s == this )
			throw new RuntimeException(
				"can not add a node at itself!" );
		this.childs.add( s );
	}

	/**
	 * generates a xml representation of this statement
	 * @param out is the writer where to append the xml
	 * @param table is the symboltable to decode symbols
	 * @throws IOException
	 */
	public void genXml( Writer out, ISymbolTable table )
		throws IOException
	{
		out.write( "<fact class=\"" );
		out.write( getClass().getName() );
		out.write( "\">" );
		out.write( "<name>" );
		if( table != null )
			out.write( table.decode( getName() ) );
		else
			out.write( Integer.toString( getName() ) );
		out.write( "</name>" );

		out.write( "<parameters>" );
		Iterator i = getRelation().getValues();
		while( i.hasNext() )
		{
			out.write( "<parameter>" );
			if( table != null )
				out.write( table.decode( (IAtom) i.next() ) );
			else
				out.write( i.next().toString() );

			out.write( "</parameter>" );
		}
		out.write( "</parameters>" );

		Iterator i2 = this.childs.iterator();
		while( i2.hasNext() )
		{
			((IStatement)i2.next()).genXml( out, table );
		}

		out.write( "</fact>" );
	}
}
