package view;

import java.awt.Color;
import java.awt.Component;
import java.awt.Font;

import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;

import animation.Memory;
import animation.Memory.MemoryType;
import animation.PseudoCodeNode;
import lib.TextLayoutHelper;

/**
 * A tree-like display of pseudocode.
 * Extends {@link DefaultTreeCellRenderer}
 * @author kolja
 *
 */
public class PseudoCodeRenderer extends DefaultTreeCellRenderer {
	
    private static final long serialVersionUID = 1L;
    
    private Color specialColor = null;
    
    private Memory mem;
    private String toolTip = "";
    
    public void setMemory( Memory m )
    {
        mem = m;
    }

    @Override
    public Color getBackgroundNonSelectionColor() {
        if(specialColor != null) {
            return specialColor;
        } else {
            return RenderHelper.BACKGROUND_COLOR;
        }
    }
    
    @Override
    public Color getForeground() {
        return new Color(0xa9b7c6);
    }
    
    @Override
    public Font getFont() {
        return new Font("Monospaced", Font.PLAIN, 12);
    }
    
    @Override
    public String getToolTipText()
    {
        return toolTip;
    }
    
    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean arg2, boolean arg3, boolean arg4, int arg5, boolean arg6) {
        PseudoCodeNode node = (PseudoCodeNode) value;
        this.doLayout();
        this.setClosedIcon( null );
        this.setOpenIcon( null );
        this.setLeafIcon( null );
        super.getTreeCellRendererComponent(tree, value, arg2, arg3, arg4, arg5, arg6);
        specialColor = null;
        if(node.isSelected()) {
            specialColor = new Color(0x2d6099);
        } else if (node.hasBreakPoint()) {
            specialColor = RenderHelper.BREAKPOINT_COLOR;
        }
        setText((String)node.getUserObject());
        toolTip = "<html>";
        for( String var : TextLayoutHelper.getVariables( (String)node.getUserObject() ) )
        {
            if( mem != null && mem.isSomewhereDefined( var, MemoryType.LOCAL ) )
            {
                Object val = mem.read( var, MemoryType.LOCAL );
                toolTip += var + "=" + val.toString() + "<br>";
            }
        }
        if( toolTip.equals( "<html>" ) )
            toolTip += "no variables found in the stack";
        else
            toolTip = toolTip.substring( 0, toolTip.length() - 4 );
        toolTip += "</html>";
        return this;
    }

}
