package view;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

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

import animation.PseudoCodeNode;

public class PseudoCodeRenderer extends DefaultTreeCellRenderer {
    
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    boolean specialColor = false;

    @Override
    public Color getBackgroundNonSelectionColor() {
        if(specialColor) {
            return Color.GREEN;
        } else {
            return null;
        }
    }
    
    private int countChildren( TreeNode treeNode )
    {
        if( treeNode.isLeaf() )
            return 0;
        else
        {
            int sum = 0;
            for( int i = 0; i < treeNode.getChildCount(); i++ )
            {
                sum += countChildren( treeNode.getChildAt( i ) ) + 1;
            }
            return sum;
        }
    }

    private int getLineNumber( TreeNode treeNode )
    {
        TreeNode parent = treeNode.getParent();
        if( parent == null )
            return 1;
        int sum = getLineNumber( parent ) + 1;
        for( int i = 0; i < parent.getChildCount(); i++ )
        {
            if( i == parent.getIndex( treeNode ) )
                return sum;
            sum += countChildren( parent.getChildAt( i ) ) + 1;
        }
        return 0;
    }

    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean arg2, boolean arg3, boolean arg4, int arg5, boolean arg6) {

        PseudoCodeNode node = (PseudoCodeNode) value;
        BufferedImage rowNumerImg = new BufferedImage( 30, 30, BufferedImage.TYPE_INT_ARGB );
        Graphics2D g = (Graphics2D) rowNumerImg.getGraphics();
        if( node.hasBreakPoint() )
        {
            g.setColor( Color.RED );
            g.fillOval(20, 10, 10, 10 );
        }
        g.setColor( Color.BLACK );
        g.drawString( "" + getLineNumber( (TreeNode) value ), 5, 20 );
        g.dispose();
        this.setClosedIcon( new ImageIcon( rowNumerImg ) );
        this.setOpenIcon( new ImageIcon( rowNumerImg ) );
        this.setLeafIcon( new ImageIcon( rowNumerImg ) );
        Component c = super.getTreeCellRendererComponent(tree, value, arg2, arg3, arg4, arg5, arg6);
        specialColor = false;
        if(node.isSelected()) {
            specialColor = true;
        }
        return c;
    }

}
