package cnp.ew.diagram;

import java.awt.*;
import java.util.*;

import cnp.ew.lightweight.*;

// QUESTION.  Are start drag, drag, etc. in Global  coords?  I think so...

public class CpConnectingHandle extends CpHandle
{
    static CpDependentLineLc connectionLine;
    static CpRubberRectangleLc connectionFeedbackGo;
    CpConnectionPolicy connectionPolicy;
    CpConnector connector;
    CpDiagrammableLc feedbackPeer;

    public CpConnectingHandle(CpDiagrammableLc newOwner, CpLocator newLocator, CpConnector newConnector, CpConnectionPolicy newConnectionPolicy)
    {
        super(newOwner, newLocator);
        connector = newConnector;
        connectionPolicy = newConnectionPolicy;
    }

	public void startDrag(int x, int y)
	{
	    Vector points = new Vector();
	    points.addElement(getPoint());
	    points.addElement(getPoint());
	    connectionLine = new CpDependentLineLc(points);
	    connectionLine.endDecoration = connectionLine.DOT;
	    owner.getDiagram().add(connectionLine);
	}

	public void drag(int x, int y)
	{
	    connectionLine.setPoint(1, new Point(x, y));

        // Show feedback if they are over a connectable go
        if (connectionFeedbackGo != null) {
            if (!feedbackPeer.insideDiagram(x, y)) {
                connectionFeedbackGo.remove();
                connectionFeedbackGo = null;
                feedbackPeer = null;
            }
        } else {
            CpDiagrammableLc peer;
            Vector peers = owner.getSiblings();
	        for (int i = 0; i < peers.size(); i++) {
	            peer = (CpDiagrammableLc)peers.elementAt(i);
	            if (peer == connectionLine) {
	                continue;
	            }
    	        if (peer.insideDiagram(x,y) && connectionPolicy.canConnect(owner, peer)) {
    	           // System.out.println("Trying to connect to " + peer + " boundsDiagram = " + peer.boundsDiagram());
	                Rectangle peerBounds = peer.boundsDiagram();
	                connectionFeedbackGo = new CpRubberRectangleLc(peerBounds.x - 10, peerBounds.y - 10, peerBounds.width + 20, peerBounds.height + 20);
	                owner.getDiagram().add(connectionFeedbackGo);
	                feedbackPeer = peer;
    	        }
    	    }
	    }
	}

	public void endDrag(int x, int y)
	{
        if (connectionFeedbackGo != null) {
            connectionFeedbackGo.remove();
        }
        connectionLine.remove();
        if (feedbackPeer != null) {
            connector.connect(owner, feedbackPeer);
        }
        connectionLine = null;
        connectionFeedbackGo = null;
        feedbackPeer = null;
    }
}