package prolog.demonstration;

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

public class DemoProgram extends Program
{
	/**
	 * the animation tree
	 */
	protected Tree tree = null;

	/**
	 * constructor
	 */
	public DemoProgram( Tree tree )
	{
		this.tree = tree;
	}

	/**
	 * the method processing the program
	 * @throws ParameterMatchingError
	 */
	public void run()
		throws ParameterMatchingError
	{
		logger.msg( "running...");

		final RootNode root = new RootNode();
		root.setContent( "queries" );
		tree.setRoot( root );

		try
		{
			Iterator i=querys.getQueries();
			while( i.hasNext() )
			{
				IFact action= (IFact) i.next();
				IFactList matching = null;
				IStatement s = statements.getMatchingStatement( action );
				logger.msg( action.toString( symbolTable ) );
				if( s != null )
				{
					((IDemoStatement)s).resetNode();
					root.addChild( ((IDemoStatement)s).getNode() );
					IFactList results = s.query( action, facts, statements );
					logFinalResult( results.getRelation(), results.getRelations() );
				}
				else if( (matching=facts.getFactList( action.getName() )) != null )
				{
					IFactList results = matching.getMatchings( action );

					Node n = new Node();
					StatementResult c = new StatementResult();
					c.setTitle( action.toString() );
					c.setResult( results );
					n.setContent( c );
					root.addChild( n );
					logFinalResult( results.getRelation(), results.getRelations() );
				}
				else
				{
					throw new ParameterMatchingError(
						"Could not resolve symbol " + action.toString( symbolTable ), null );
				}
			}
		}
		catch( ParameterMatchingError err )
		{
			err.printStackTrace();
			onException( err );
		}
		catch( Throwable t )
		{
			t.printStackTrace();
			onException( t );
		}
	}

	public static void onException( final Throwable t )
	{
		SwingUtilities.invokeLater(
			new Runnable()
			{
				public void run()
				{
					JOptionPane.showMessageDialog(
						null,
						t.getMessage(),
						"An error occured",
						JOptionPane.ERROR_MESSAGE );
				}
			}
		);
	}
}
