import objectdraw.*;
import java.awt.*;
import java.util.ArrayList;

/* $Id: DragAllRoadsArrayList.java 1585 2011-03-31 04:00:23Z terescoj $ */

/**
 * Example DragAllRoadsArrayList: draw "road segments" at mouse press
 * points, but drag any existing segment instead if it happens to
 * contain the mouse press point.
 *
 * This version uses an ArrayList to store the segments.
 *
 * @author Jim Teresco
 * Siena College, CSIS 120, Fall 2011
 *
 */

public class DragAllRoadsArrayList extends WindowController {
    
    // the road segments in our drawing
    private ArrayList<RoadSegment> segments;
    
    // the road segment currently being dragged, if any
    private RoadSegment selectedSegment;
    
    // last mouse point and boolean flag to support dragging
    private boolean dragging;
    private Location lastMouse;
    
    /**
     * Set up: just initialize the array of segments
     * and set other instance variables.
     */
    public void begin() {
    
        segments = new ArrayList<RoadSegment>();
        selectedSegment = null;
        dragging = false;
        lastMouse = null;
    }
    
    /** Draw a road segment at the mouse press point
     *  unless the most recent road drawn was at that
     *  point, in which case we begin a drag operation.
     * 
     *  @param point the Location of the mouse press
     */
    public void onMousePress(Location point) {
    
        // see if we've pressed the mouse on an existing road segment
        for (int segmentNum = 0; segmentNum < segments.size(); segmentNum++) {
            
            if (segments.get(segmentNum).contains(point)) {
                selectedSegment = segments.get(segmentNum);
                dragging = true;
                lastMouse = point;
            }
        }
        
        // if dragging is still false, we create a new segment
        if (!dragging) {
            
             // create the new segment and insert it into arraylist
            segments.add(new RoadSegment(point, canvas));
            dragging = false;
        }
    }
    
    /** Perform dragging operation if we are dragging anything
     * 
     *  @param point the Location of the mouse press
     */
    public void onMouseDrag(Location point) {
     
        if (dragging) {
            selectedSegment.move(point.getX() - lastMouse.getX(),
                                 point.getY() - lastMouse.getY());
            lastMouse = point;
        }
    }
    
    /** Complete dragging operation if we are dragging anything
     * 
     *  @param point the Location of the mouse press
     */
    public void onMouseRelease(Location point) {
     
        if (dragging) {
            selectedSegment.move(point.getX() - lastMouse.getX(),
                                 point.getY() - lastMouse.getY());
            dragging = false;      
        }
    }  
 }
