package graphics.graph;


public class EdgesManager {
  private StressBean sb = StressBean.getStressBean();
  private EdgesBean eb = EdgesBean.getEdgesBean();
  private ColorPanel cp = GraphFactory.getColorPanel();
  private Nodes nodes = GraphFactory.getNodes();
  private ImageUtil imageUtil;
  public ControlPanel controlPanel;

  private ImageUtil getImageUtil()
      /**
       *    This is created using laissez-faire initialization
       *    because you cannot reference this in the constructor
       */ {
    if (imageUtil == null) {
      imageUtil = GraphFactory.getImageUtil();
    }
    return imageUtil;
  }

  public void drawArcAndString(int i) {
    // Edge e = edges[i];
    Edge e = eb.getEdge(i);

    Node fromNode = nodes.getNode(e.getFrom());
    int x1 = (int) fromNode.getX();
    int y1 = (int) fromNode.getY();
    Node toNode = nodes.getNode(e.getTo());
    int x2 = (int) toNode.getX();
    int y2 = (int) toNode.getY();
    int dx = (x1 - x2);
    int dy = (y1 - y2);
    int len = (int) Math.abs(Math.sqrt(dx * dx + dy * dy) - e.getLen());
    getImageUtil().getOffGraphics().setColor((len < 10)
                                             ? cp.getArcColor1()
                                             : (len < 20 ? cp.getArcColor2() : cp.getArcColor3()));
    getImageUtil().getOffGraphics().drawLine(x1, y1, x2, y2);
    if (sb.getStress())
      drawArcString(len, x1, x2, y1, y2);
  }

  private void drawArcString(int len, int x1, int x2, int y1, int y2) {
    String lbl = String.valueOf(len);
    getImageUtil().getOffGraphics().setColor(cp.getStressColor());
    getImageUtil().getOffGraphics().drawString(
        lbl, x1 + (x2 - x1) / 2, y1 + (y2 - y1) / 2);
    getImageUtil().getOffGraphics().setColor(cp.getEdgeColor());
  }

  public void setupEdges() {
    for (int i = 0; i < eb.getNumberOfEdges(); i++) {
      // Edge e = edges[i];
      Edge e = eb.getEdge(i);
      double vx = nodes.getNode(e.getTo()).getX()
          - nodes.getNode(e.getFrom()).getX();
      double vy = nodes.getNode(e.getTo()).getY()
          - nodes.getNode(e.getFrom()).getY();
      double len = Math.sqrt(vx * vx + vy * vy);
      len = (len == 0) ? .0001 : len;
      double f = (e.getLen() - len)
          / (len * 3);
      double dx = f * vx;
      double dy = f * vy;

      nodes.getNode(e.getTo()).incrementDxDy(dx, dy);
      nodes.getNode(e.getFrom()).incrementDxDy(-dx, -dy);
    }
  }
}