package trees;

import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.util.Collection;
import java.util.LinkedList;

import points.DrawableNamedPoint;

public class TreeNode implements DrawableNamedPoint {
  private String name;
  private int px;
  private int py;
  private LinkedList<TreeNode> children;
  private TreeNode parent;

  public TreeNode(String s, int x, int y) {
    name = s;
    px = x;
    py = y;
    children = new LinkedList<TreeNode>();
  }

  // pour l'interface NamedPoint
  public String getName() {
    return name;
  }
  public int getX() {
    return px;
  }
  public int getY() {
    return py;
  }

  // pour l'interface Drawable
  public void paint(Graphics g) {
    String name = getName();
    int x = getX();
    int y = getY();
    FontMetrics m = g.getFontMetrics();
    int rad = m.getAscent();
    int len = m.stringWidth(name);
    g.setColor(Color.lightGray);
    g.fillOval(x - len / 2 - rad, y - rad, len + 2 * rad, 2 * rad);
    g.setColor(Color.black);
    g.drawOval(x - len / 2 - rad, y - rad, len + 2 * rad, 2 * rad);
    g.drawString(name, x - len / 2, y + (m.getAscent() - m.getDescent()) / 2);
  }

  // autre mŽthodes

  TreeNode fetch(String name) {
    if (name.equals(this.name))
      return this;
    else
      for (TreeNode t : children) {
        TreeNode tt = t.fetch(name);
        if (tt != null)
          return tt;
      }
    return null;
  }

  public void addChild(TreeNode child) {
    children.addLast(child);
    child.parent = this;
  }

  public TreeNode getParent() {
    return parent;
  }

  public Collection<DrawableNamedPoint> getChildren() {
    return new LinkedList<DrawableNamedPoint>(children);
  }

  public String toString() {
    return name + " (" + px + ',' + py + ')';
  }
}

