package prolog.ui;

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

public class FactListRenderer
{
	protected ISymbolTable ivSymbolTable = null;
	protected static final Dimension gvCellSize = new Dimension( 50, 20 );

	public FactListRenderer( ISymbolTable symbolTable )
	{
		this.ivSymbolTable = symbolTable;
	}

	public Dimension getDimension( IFactList l )
	{
		if( l == null )
			return gvCellSize;

		int w = gvCellSize.width * l.getColCount();
		int h = gvCellSize.height + (gvCellSize.height*l.getRowCount());
		if( l.getRelation() != null && l.getRelation().getValueCount() > 0 )
			h += gvCellSize.height;
		return new Dimension( w+10, h );
	}

	public void render( Graphics2D g, Rectangle rect, IFactList l )
	{
		IRelation headerRelation = l.getRelation();
		int colCount = 0;
		if( headerRelation != null )
			colCount = headerRelation.getValueCount();
		int y = rect.getLocation().y;

		// paint header
		UiUtil.paintCenteredCell(
			g,
			new Rectangle(
				rect.getLocation().x,
				y,
				gvCellSize.width*l.getColCount(),
				gvCellSize.height ),
				ivSymbolTable != null ? ivSymbolTable.decode( l.getName() ) : Integer.toString( l.getName() ),
				Color.orange,
				Color.darkGray );
		y += gvCellSize.height;

		// paint column header
		if( colCount > 0 && headerRelation != null )
		{
			Iterator headers = headerRelation.getValues();
			for( int i=0;i<colCount;i++ )
			{
				IAtom atom = (IAtom) headers.next();
				UiUtil.paintCenteredCell(
					g,
					new Rectangle(
						rect.getLocation().x + (i*gvCellSize.width),
						y,
						gvCellSize.width,
						gvCellSize.height ),
					ivSymbolTable != null ?
						ivSymbolTable.decode( atom.getName() ) :
						Integer.toString( atom.getName() ),
					Color.lightGray,
					Color.darkGray );
			}
			y += gvCellSize.height;
		}

		// paint content
		Iterator rows = l.getRelations();
		while( rows.hasNext() )
		{
			IRelation r = (IRelation) rows.next();
			Iterator values = r.getValues();
			colCount = r.getValueCount();
			for( int i=0;i<colCount;i++ )
			{
				IAtom atom = (IAtom) values.next();
				UiUtil.paintCell(
					g,
					new Rectangle(
						rect.getLocation().x + (i*gvCellSize.width),
						y,
						gvCellSize.width,
						gvCellSize.height ),
					ivSymbolTable != null ?
						ivSymbolTable.decode( atom.getName() ) :
						Integer.toString( atom.getName() ),
					Color.white,
					Color.darkGray );
			}
			y += gvCellSize.height;
		}
	}
}
