package org.khelekore.jsizer;

import java.awt.Color;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/** A graphical node. */
class TreeNode {
    private String name;
    private int x;
    private int y;
    private int width;
    private int height;
    private int z;
    private int childWidth = -1;
    private Color color;
    private Rectangle rect;
    private List<TreeNode> children;

    public TreeNode (String name) {
	this (name, 3, 3, -1, Color.GREEN);
    }

    public TreeNode (String name, int width, int height, int z, Color color) {
	this.name = name;
	this.width = width;
	this.height = height;
	this.z = z;
	this.color = color;
    }

    @Override public String toString () {
	return getClass ().getSimpleName () + "{" + name + 
	    ", rect: " + rect + ", child width: " + childWidth + "}";
    }

    public String getName () {
	return name;
    }

    public boolean isPackage () {
	return z == -1;
    }

    public Color getColor () {
	return color;
    }

    public int getWidth () {
	return width;
    }

    public int getGraphicalWidth () {
	return 2 * (width + 1);
    }

    public int getHeight () {
	return height;
    }

    public int getGraphicalHeight () {
	return 2 * (height + 1);
    }

    public int getZ () {
	return z;
    }

    public Rectangle getRectangle () {
	if (rect == null) {
	    int w = getGraphicalWidth ();
	    int h = getGraphicalHeight ();
	    rect = new Rectangle (x - w / 2, y - h / 2, w, h);
	}
	return rect;
    }
    
    public void setPosition (int x, int y) {
	this.x = x;
	this.y = y;
	rect = null;
    }

    public Point getCenterTop () {
	return new Point (x, y - getGraphicalHeight () / 2);
    }
    
    public Point getCenterBottom () {
	return new Point (x, y + getGraphicalHeight () / 2);
    }

    public void addChild (TreeNode tn) {
	if (children == null)
	    children = new ArrayList<TreeNode> ();
	children.add (tn);
    }

    public int getWidthWithChildren () {
	int w = getGraphicalWidth ();
	if (children == null)
	    return w;
	int cw = getChildrenWidth ();
	return Math.max (cw, w);
    }

    public int getChildrenWidth () {
	if (children == null)
	    return 0;
	if (childWidth < 0) {
	    childWidth = 0;
	    for (TreeNode tn : children)
		childWidth += tn.getWidthWithChildren () + 2;
	}
	return childWidth;
    }

    public List<TreeNode> getChildren () {
	if (children == null)
	    return Collections.<TreeNode>emptyList ();
	return children;
    }
}
