package prolog.demonstration;

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

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

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

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

	/**
	 * constructor 2
	 * @param f - the fact from which to take the parameters
	 */
	public DemoMatchingStatement( Tree tree, int name, IRelation relation )
	{
		super( name, relation );
		this.tree = tree;
	}

	/**
	 * querries the fact database for a entity that can handle the querry.
	 * this can be a factlist or another statement.
	 * @param f
	 * @param l
	 * @param constraints
	 * @return
	 * @throws ParameterMatchingError
	 */
	public IFactList query( IFact f, IFactDb l, IStatementMap constraints  )
		throws ParameterMatchingError
	{
		IFactList back = null;

		IFactList rl = l.getFactList( f.getName() );
		if( rl == null )
		{
			IStatement s = constraints.getStatement( f.getName() );
			IDemoStatement ds = (IDemoStatement) s;
			if( s == null )
				throw new ParameterMatchingError( "FATAL ERROR: MatchingNode.query failed!", f );
			else
			{
				this.getNode().addChild( ds.getNode() );
				back = s.query( f, l, constraints );
			}
		}
		else
		{
			back = rl.getMatchings( f );
		}

		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;
	}

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

	/**
	 * clears the cached node
	 */
	public void resetNode()
	{
		this.thisNode = null;
	}

	public String toString()
	{
		return toString( SingletonFactory.getBuilder().getSymbolTable() );
	}
}
