/**
 *  Licensed under GPL. For more information, see
 *    http://jaxodraw.sourceforge.net/license.html
 *  or the LICENSE file in the jaxodraw distribution.
 */

package net.sf.jaxodraw.gui.panel;

import java.awt.Component;
import java.awt.Cursor;
import java.awt.Point;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

/**
 * The glassPane object for the main panel.
 *
 * @since 2.1
 */
public final class JaxoGlassPane extends JComponent {
    private static final long serialVersionUID = 75264711556226147L;
    private final JFrame theParent;
    private final JComponent theViewPort;

    /**
     * Constructor.
     *
     * @param parent the parent Frame.
     * @param viewPort the view port.
     */
    public JaxoGlassPane(final JFrame parent, final JComponent viewPort) {
        super();
        this.theParent = parent;
        this.theViewPort = viewPort;

        setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(final MouseEvent e) {
                stopPointMouseAction(); // Click outside canvas stops
            }
        });
    }

    private void stopPointMouseAction() {
        final Action action = theViewPort.getActionMap().get("stopPointMouseAction");

        if (action != null) {
            action.actionPerformed(null);
        }
    }

    /** {@inheritDoc} */
    @Override
    public boolean contains(final int x, final int y) {
        final Point p = SwingUtilities.convertPoint(this, new Point(x, y),
                theParent.getContentPane());
        Component c = theParent.getContentPane().findComponentAt(p);

        // Allow the canvas itself
        if (c == theViewPort) {
            return false;
        }

        // Allow components within the JScrollPane
        while (!(c instanceof JScrollPane) && (c != null)) {
            c = c.getParent();
        }

        if ((c != null) && (((JScrollPane) c).getViewport().getView() == theViewPort)) {
            return false;
        }

        // disallow the rest
        return true;
    }
}
