import java.awt.event.*;
import java.awt.*;
import java.lang.Math;


class RotarHandler implements ActionListener
{
	private EditorPanel panel;
	private Point ancla;
	private double anguloReferencia;
	private Cruz cruz;
	private int state;
	private Forma forma;
	private static final int INICIO_NUEVA_ROTACION=0;
	private static final int FORMA_SELECCIONADA=1;
	private static final int ANCLA_FIJADA=2;
        private static final int TERMINO_ROTACION=3;

	public RotarHandler(EditorPanel panel)
	{
		this.panel = panel;
		cruz = new Cruz();
	}

	public void actionPerformed(ActionEvent e)
	{
      		panel.changeMouseListener(new MouseHandler());
      		panel.changeMouseMotionListener(new MouseMotionHandler());
      		state = INICIO_NUEVA_ROTACION;
    		panel.manipulating();
	}		

	class MouseHandler extends MouseAdapter
	{
		public void mouseClicked(MouseEvent event)
		{
			if(state==INICIO_NUEVA_ROTACION)
			{
				Point punto=event.getPoint();
				forma=(Forma)panel.find(punto);	
			
				if(forma!=null)
				{
					state=FORMA_SELECCIONADA;
					panel.nomanipular();
					forma.setManipulable(true);
					panel.repaint();
				}
			}

			else if(state==FORMA_SELECCIONADA)
			{
				ancla = event.getPoint();
				panel.remueva(cruz);
				cruz.setPoint(ancla);
				panel.incorpore(cruz);
				state = ANCLA_FIJADA;
			}
		}
		
		public void mousePressed(MouseEvent event)
		{
			if (state==ANCLA_FIJADA)
			{
				Point p =event.getPoint();
				double x = p.getX()-ancla.getX();
				double y = p.getY()-ancla.getY();
				anguloReferencia = Math.atan2(y,x);
			}
        		if (state==TERMINO_ROTACION)
          		{
				panel.manipulating();
				state=INICIO_NUEVA_ROTACION;			
			}
		}
		
		public void mouseReleased(MouseEvent event)
		{
			if(state==ANCLA_FIJADA)
			{
				panel.remueva(cruz);
				state = TERMINO_ROTACION;
			}
		}
	}

	class MouseMotionHandler extends MouseMotionAdapter
	{
		public void mouseDragged(MouseEvent event)
		{
			if(state==ANCLA_FIJADA)
			{
				Point p = event.getPoint();
			        double x = p.getX()-ancla.getX();
          			double y = p.getY()-ancla.getY();
          			double nuevoAngulo = Math.atan2(y, x);
          			double deltaAngulo= nuevoAngulo-anguloReferencia;
          			forma.rotar(ancla, deltaAngulo);
          			anguloReferencia= nuevoAngulo;
        			panel.repaint();
			}
      		}
  	}	  
}	
					
					
