// An Applet that demonstrates basic object-oriented design.
// The user can move the line segments once they have been drawn.
// S. Tanimoto -- 31 Jan. 2000

// Note: Determining and displaying an intersection between two segments
// is initially the responsibility of the later-created segment. If the segment
// that is NOT responsible for the intersection is updated, the updated
// intersection will be drawn all right, but the original intersection will
// continue to be shown until the line segment responsible for it is itself
// moved at least a little. Fixing this is left as an optional exercise.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class LineSegmentCollectionD extends Applet {
  Vector theSegments;
  LSPointD selectedPoint = null;
  LineSegmentD selectedLS = null;

  public void init() {
    MyMouseHandler mmh = new MyMouseHandler();
    addMouseListener(mmh);
    addMouseMotionListener(mmh);

    theSegments = new Vector();
    for (int i = 0; i < 10; i++) {
      theSegments.addElement(new LineSegmentD(i, this));
    }
  }

  public void paint(Graphics g) {
    setBackground(Color.red);
    g.setColor(Color.black);
    for (Enumeration theEnum = theSegments.elements();
      theEnum.hasMoreElements();) {
        ((LineSegmentD)theEnum.nextElement()).paint(g);
    }
  }

  public Vector otherSegments(LineSegmentD oneSegment) {
    Vector copyOfList = (Vector)(theSegments.clone());
    copyOfList.removeElement((Object)oneSegment);
    return copyOfList;
  }

  class MyMouseHandler extends MouseAdapter implements MouseMotionListener {

    public void mousePressed (MouseEvent e) {
      for (Enumeration theEnum = theSegments.elements();
        theEnum.hasMoreElements();) {
        selectedLS = (LineSegmentD)theEnum.nextElement();
        selectedPoint = selectedLS.getHit(e.getX(), e.getY());
        if (selectedPoint != null) break;
        selectedLS = null;
      }
    }

    public void mouseReleased (MouseEvent e) {
      selectedPoint = null;
    }

    public void mouseDragged (MouseEvent e) {
      if (selectedPoint != null)
        selectedLS.updateLocation(selectedPoint, e.getX(), e.getY());
      repaint();
    }

    public void mouseMoved (MouseEvent e) {}
    }
}