import objectdraw.*;
import java.awt.*;

/*
 * Example Drag10Shirts
 *
 * Drag one of 10 shirts around window.
 *
 * Jim Teresco, Siena College, CSIS 120, Fall 2011
 *
 * $Id: Drag10Shirts.java 1576 2011-03-24 04:32:40Z terescoj $
 */

public class Drag10Shirts extends WindowController {

    // starting location of t-shirts
    private static final int ITEM_LEFT = 30;
    private static final int ITEM_TOP = 50;
    private static final int SND_OFFSET = 90;

    // how many shirts to draw
    private static final int NUM_SHIRTS = 10;

    // T-shirts on the screen -- an array!
    private TShirt[] shirts;

    // The piece of laundry to be moved.
    private TShirt selectedShirt;

    // Previously noted position of mouse cursor
    private Location lastPoint;

    // Whether user is actually dragging a shirt
    private boolean dragging;

    // display the shirts
    public void begin() {

        // construct the array that can hold our 10 shirts
        shirts = new TShirt[NUM_SHIRTS];

        // now create the shirts -- with random colors for now
        RandomIntGenerator colorGen = new RandomIntGenerator(0, 255);
        int nextShirtPos = ITEM_LEFT;

        for (int shirtNum = 0; shirtNum<NUM_SHIRTS; shirtNum++) {

            shirts[shirtNum] = new TShirt(nextShirtPos, ITEM_TOP, canvas);
            shirts[shirtNum].setColor(new Color(colorGen.nextValue(), colorGen.nextValue(), colorGen.nextValue()));

            nextShirtPos = nextShirtPos + SND_OFFSET;
        }

        selectedShirt = shirts[0]; // first shirt on top at start
    }

    // Whenever mouse is depressed, note its location
    // and which (if any) shirt the mouse is on.
    public void onMousePress(Location point) {
        lastPoint = point;

        dragging = false;
        // test the selected shirt (which is on top) first.
        if (selectedShirt.contains(point)) {
            dragging = true;
        } else {
            for (int shirtNum = 0; shirtNum<NUM_SHIRTS; shirtNum++) {
                if (shirts[shirtNum].contains(point)) {
                    selectedShirt = shirts[shirtNum];
                    dragging = true;
                    selectedShirt.sendToFront();
                }
            }
        }
    }

    // If mouse is dragged, move the selected shirt with it
    // If didn't press mouse on a shirt, do nothing
    public void onMouseDrag(Location point) {
        if (dragging) {
            selectedShirt.move(point.getX() - lastPoint.getX(),
                point.getY() - lastPoint.getY());
            lastPoint = point;
        }
    }

    // move both shirts back to starting positions when mouse leaves window
    public void onMouseExit(Location point) {

        for (int shirtNum = 0; shirtNum<NUM_SHIRTS; shirtNum++) {
            shirts[shirtNum].reset();
        }
        dragging = false;
    }
}
