package graphics.graph;

import java.awt.*;

public class RelaxThreadMgr implements Runnable
    /**
     *  This class used to be the RelaxPanel and before that all of the
     *  code here was included in the GraphPanel.
     *  Its responsibility is to maintain a Thread that will randomly
     *  "relax" or move the nodes around once every 1/10 of a second.
     *  A Component is passed in as part of the Constructor. After the
     *  appropriately "relaxing" has been calculated, a message is sent
     *  to repaint the component.
     */ {
  private boolean random;
  private Nodes nodes = GraphFactory.getNodes();
  private Thread relaxerThread = new Thread(this);
  private EdgesManager em = GraphFactory.getEdgesManager();
  private Component component = null;

  public RelaxThreadMgr(Component c) {
    component = c;
  }

  private void relaxer(Thread me) {
    while (relaxerThread == me) {
      relax();
      if (random && (Math.random() < 0.03)) {
        Node n = nodes.getRandomNode();
        if (!n.isFixed())
          Node.nIsNotFixed(n);
      }
      try {
        Thread.sleep(100);
      } catch (InterruptedException e) {
        break;
      }
    }
  }

  public void setRandom(boolean b) {
    random = b;
  }

  synchronized void relax() {
    em.setupEdges();
    for (int i = 0; i < nodes.getNumberOfNodes(); i++)
      nodes.preturbJRelativetoI(i, nodes.getNode(i));
    for (int i = 0; i < nodes.getNumberOfNodes(); i++)
      nodes.getNode(i).nugeNode(
          component.getSize());
    component.repaint();
  }

  public void start() {
    relaxerThread = new Thread(this);
    relaxerThread.start();
  }

  public void run() {
    relaxer(Thread.currentThread());
  }
}