import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Dimension;
import java.awt.RenderingHints;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.Color;

/**
 * @author Milan Ruzicka
 *
 */

public class AngleChooser extends JPanel implements MouseListener, MouseMotionListener {

	static final long serialVersionUID = 40L;
	
	public final int xSize = 50;
	public final int ySize = 50;
	
	private Tool tool;
	
	public double angle = 0;
	public int angleDeg = 0; 
	
	public AngleChooser(Tool t){
		this();
		tool = t;
	}
	
	public AngleChooser(Tool t, double a){
		this();
		tool = t;
		angle = a;
	}
	
	public AngleChooser() {
		setSize(xSize, ySize);
		setPreferredSize(new Dimension(xSize,ySize));
		addMouseListener(this);
		addMouseMotionListener(this);
	}
	
	public void paint(Graphics g1){
		super.paint(g1);		
		Graphics2D g = (Graphics2D)g1;
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g.setColor(Color.BLACK);
		g.drawArc(0, 0, xSize-1, ySize-1, 0, 360);
		g.drawLine(xSize/2-1, ySize/2-1, Math.round(xSize/2 -1 + (float)(Math.cos(angle)*(xSize/2-1))), ySize/2 -1 + Math.round((float)(Math.sin(angle)*(ySize/2-1))) );
	}
	
	public void mouseClicked(MouseEvent e){
		int x = e.getX() - xSize/2;
		int y = e.getY() - ySize/2;
		
		if (y>=0){
			angle = Math.acos((double)x/(Math.sqrt(x*x+y*y)));
		}
		else{
			angle = Math.acos(-(double)x/(Math.sqrt(x*x+y*y))) + Math.PI;
		}
		
		angleDeg = (int)Math.round(angle * 180 / Math.PI);
		repaint();
		
		if (tool!=null) tool.angle = angle;
		
	}
	
	public double getAngle(){
		return angle;
	}
	
	public int getAngleDeg(){
		return angleDeg;
	}
	
	public void mouseDragged(MouseEvent e){
		int x = e.getX() - xSize/2;
		int y = e.getY() - ySize/2;
		
		if (y>=0){
			angle = Math.acos((double)x/(Math.sqrt(x*x+y*y)));
		}
		else{
			angle = Math.acos(-(double)x/(Math.sqrt(x*x+y*y))) + Math.PI;
		}
		angleDeg = (int)Math.round(angle * 180 / Math.PI);
		
		if (tool!=null) tool.angle = angle;
		repaint();
	}
	
	public void mousePressed(MouseEvent e){
		
	}
	
	public void mouseEntered(MouseEvent e){
		
	}
	
	public void mouseReleased(MouseEvent e){
		
	}
	
	public void mouseExited(MouseEvent e){
		
	}
	
	public void mouseMoved(MouseEvent e){
		
	}

}