package Darts;

import java.util.Enumeration;
import javax.swing.table.AbstractTableModel;


public class DartTableModel extends AbstractTableModel {
	//
	// Member Data
	//
	private static final long serialVersionUID = 1L;
	private DartDBNode 		  game; // Pointers to game to display.
	private boolean detailedDisplay = false;

    
	//
	// Methods
	//
    
	/**
	 * Constructor:
	 */
    public DartTableModel() {
    	game = null;
	}

	public int getColumnCount() {
		if( game == null )
			return 0;
		int  maxCount = 0;

		for( Enumeration<DartDBNode> e1 = game.children() ; e1.hasMoreElements() ;) {
			DartDBNode player = e1.nextElement();
			if( player.getChildCount() > maxCount ) {
				maxCount = player.getChildCount();
			}
		}
	return maxCount + 1; // Plus one for names
	}

    public int getRowCount() {
		if( game == null )
			return 0;
        return game.getChildCount();
    }

    @Override
	public String getColumnName( int col ) {
    	if( col == 0 )
    		return "Player";
        return "Round #" + col;
    }

  public Object getValueAt(int row, int col) {
		// Return the player's name in first col
		if (col == 0)
			return game.getChildAt(row).toString(); // <--------------- RETURN

		DartDBNode  player = (DartDBNode) game.getChildAt(row);

		// Return nothing if this player hasn't played this many rounds.
		if (col > player.getChildCount())
			return "";
		DartDBNode  score = ( (DartDBNode) (player.getChildAt(col-1)) );
	
		DisplayScore  displayScore = score.calculateScore();
    if( detailedDisplay )
    	{
			String  stealee = "";
			String  stealer = "";
			if( displayScore.gained > 0 )
				stealee = ((DartDBNode) score.stealeeScore().getParent()).toString()
						+ displayScore.gained + "--> ";
			if( displayScore.lost > 0 )
				stealer = " -->"
						+ ((DartDBNode) score.stealerScore().getParent()).toString()
						+ displayScore.lost;

			return stealee + displayScore.toString() + stealer;
			}
    
    // Calculate the total score so far
		int total = 0;
		for( int i = 0; i < col; i++ )
			total += ((DartDBNode) (player.getChildAt(i))).calculateScore().finalScore;

    return displayScore.finalScore + " / " + total;
		}

	public void setGame(DartDBNode gameToDisplay)
		{
		game = gameToDisplay;
		fireTableStructureChanged();
		}

	public void setDetailMode( boolean theDetailedDisplay )
		{
		detailedDisplay  = theDetailedDisplay;
		fireTableStructureChanged();
		}

    /*
		 * Uneditable table.
		 */
    @Override
		public boolean isCellEditable(int row, int col) {
        return false;
    }

}
