package cz.fidentis.analyst.gui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
//import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

/**
 *
 * @author Richard Pajersky
 * 
 * 3D manipulation with mouse, using 3D movement from GeneralGLEventListener
 */
public class Manipulator3D extends MouseAdapter {
    
    private GeneralGLEventListener listener;

    private float lastX = 0;
    private float lastY = 0;
    
    private static double rotationSpeed = 0.4;
    private static double moveSpeed = 0.4;

    public Manipulator3D(GeneralGLEventListener listener) {
        this.listener = listener;
    }

    /**
     * Left mouse button dragging rotates
     * Right mouse button dragging moves
     * Middle mouse button dragging resets rotation and zoom
     */
    @Override
    public void mouseDragged(MouseEvent evt) {
        //JOptionPane.showMessageDialog(null, evt.getButton());

        if (SwingUtilities.isLeftMouseButton(evt)) {
            double rotateX = -(lastY - evt.getY()) * rotationSpeed;
            double rotateY = +(lastX - evt.getX()) * rotationSpeed;
            if (Math.abs(rotateX) < Math.abs(rotateY)) {
                rotateX = 0;
            } else if (Math.abs(rotateY) < Math.abs(rotateX)) {
                rotateY = 0;
            }
            listener.rotate(rotateX, rotateY);
        }
        if (SwingUtilities.isRightMouseButton(evt)) {
            double moveX = -(lastX - evt.getX()) * moveSpeed;
            double moveY = -(lastY - evt.getY()) * moveSpeed;
            listener.move(moveX, moveY);
        }
        if (SwingUtilities.isMiddleMouseButton(evt)) {
            listener.rotationAndSizeRestart();
        }
        lastX = evt.getX();
        lastY = evt.getY();
    }

    /**
     * Actualize mouse movement
     */
    @Override
    public void mouseMoved(MouseEvent e) {
        lastX = e.getX();
        lastY = e.getY();
    }

    /**
     * Zoom in or out based on mouse wheel movement
     */
    @Override
    public void mouseWheelMoved(MouseWheelEvent evt) {
        if (evt.getWheelRotation() > 0) {
            listener.zoomIn(-5 * evt.getWheelRotation());
        } else {
            listener.zoomOut(5 * evt.getWheelRotation());
        }
    }
    
    /**
     * Middle mouse button click resets rotation and zoom
     */
    @Override
    public void mouseClicked(MouseEvent evt) {
        if (SwingUtilities.isMiddleMouseButton(evt))
            listener.rotationAndSizeRestart();
    }
    
    public static double getRotationSpeed() {
        return rotationSpeed;
    }

    public static void setRotationSpeed(double rotationSpeed) {
        Manipulator3D.rotationSpeed = rotationSpeed;
    }

    public static double getMoveSpeed() {
        return moveSpeed;
    }

    public static void setMoveSpeed(double moveSpeed) {
        Manipulator3D.moveSpeed = moveSpeed;
    }

}
