package drawables;

import java.awt.*;
import javax.swing.*;
import uk.ac.ic.doc.automed.editor.*;
import uk.ac.ic.doc.automed.reps.SchemaObject;
import uk.ac.ic.doc.automed.InconsistentException;

public class DrawERRelationshipArc extends DrawArc {   
  int textHeight;

  /*
    For arcs your Drawable can either supply no constructor,
    in which case the noarg default constructor will be used, or you can
    provide one with the signature below to get a reference to the EditorFrame
    and the array of Positionables that represent the vertices of the arc
    before the paint method is called.
   */
  public DrawERRelationshipArc(EditorPanel ep,Positionable rel,
			       Positionable schemaObject[]) {
    super(ep,rel,schemaObject);
    textHeight=fm.getAscent(); //+fm.getDescent();
  }
  
  /*
    Draw the arc between a vertex representing the relationship in p[0] and
    an vertex representing one of the attached entities in [1]
   */
  public void paint(Graphics2D g) {

    SchemaObject rel=(SchemaObject)p;
    Object o[]=rel.getSchemeDefinition();
    String linkName=(String)o[0];

    // Which cardinality to use?
    JComponent jc1=ep.getVertexComponent(p);
    g.setColor(p.getForegroundColor());

    for (int i=0;i<d.length;i++) {
      JComponent jc2=ep.getVertexComponent(d[i]);
      String card=(String)(d[i]==o[1] ? o[3] : o[4]);
      Point[] pnt=EditorPanel.calcRectangleConnector(jc1.getBounds(),
						     jc2.getBounds());

      g.drawLine(pnt[0].x,pnt[0].y,pnt[1].x,pnt[1].y);
      cardString(g,card,pnt[1], pnt[0]);
    }
  }

  private void cardString(Graphics2D g,String s,Point p1,Point p2) {
    // Calculate which 45 degree segment the line falls in, counting
    // pos to angle range as
    // ... 0 (-45 .. 0),1 (0 .. 45), 2 (45 .. 90), ...
    int pos=(int)Math.ceil(Math.atan2(p1.y-p2.y,p2.x-p1.x)/(Math.PI/4));
    
    switch (pos) {
    case 4 : 
    case -1:
      g.drawString(s,p1.x-fm.stringWidth(s),p1.y+textHeight);
      break;

    case 2 :
    case -3:
      g.drawString(s,p1.x-fm.stringWidth(s),p1.y);
      break;

    case 1 :
    case -2:
      g.drawString(s,p1.x,p1.y+textHeight);
      break;

    default :
      g.drawString(s,p1.x,p1.y);
    }
  }
}
