package prolog.demonstration;

import java.util.*;
import prolog.model.*;
import prolog.util.*;
import prolog.implementation.*;
import prolog.treeview.*;

public class DemoAndStatement
	extends
		AndStatement
	implements
		IDemoStatement
{
	/**
	 * the animation tree
	 */
	protected Tree tree = null;

	/**
	 * the parent of this node in animation tree
	 */
	protected Node thisNode = null;

	/**
	 * constructor 1
	 */
	public DemoAndStatement( Tree tree, int name )
	{
		super( name );
		this.tree = tree;
	}

	/**
	 * constructor 2
	 */
	public DemoAndStatement( Tree tree, IFact f )
	{
		super( f.getName() );
		this.tree = tree;
		this.relation = (Relation) f.getRelation();
	}

	/**
	 * @return the node in the demo tree
	 */
	public Node getNode()
	{
		if( thisNode == null )
		{
			thisNode = new Node();
			thisNode.setContent( this );

			Iterator i = childs.iterator();
			while( i.hasNext() )
				thisNode.addChild( ((IDemoStatement)i.next()).getNode() );
		}
		return thisNode;
	}

	/**
	 * clears the cached node
	 */
	public void resetNode()
	{
		this.thisNode = null;
		Iterator i = childs.iterator();
		while( i.hasNext() )
			((IDemoStatement)i.next()).resetNode();
	}

	/**
	 * @return a string representation of this item
	 */
	public String toString()
	{
		return toString( SingletonFactory.getBuilder().getSymbolTable() );
	}

	/**
	 * queries the child nodes and calls the recursive
	 * findMatching method to merge all results.
	 * @param f - the target format
	 * @param l - the fact database
	 * @param constraints - the statements to resolve when not found in fdb
	 * @return a result factlist with all matching results in the format
	 * described in the f parameter fact
	 * @throws ParameterMatchingError
	 */
	public IFactList query( IFact f, IFactDb l, IStatementMap constraints  )
		throws
			ParameterMatchingError
	{
		IFactList back = super.query( f, l, constraints );
		if( back != null )
		{
			if( getNode().getContent() == this || getNode().getContent() == null )
			{
				StatementResult sr = new StatementResult();
				sr.setTitle( toString( SingletonFactory.getBuilder().getSymbolTable() ) );
				sr.setResult( back );
				thisNode.setContent( sr );
			}
			else
			{
				StatementResult sr = (StatementResult) getNode().getContent();
				sr.setTitle( toString( SingletonFactory.getBuilder().getSymbolTable() ) );
				sr.setResult( back );
				thisNode.setContent( sr );
			}
		}
		return back;
	}
}
