package threearms;
import java.awt.*;
import primitives.geomtry.Coordinate;
import primitives.machines.MachineException;
class constraint3ArmsMachine extends MachineSpace {
	double alpha;
	public 	constraint3ArmsMachine(Canvas drawArea,MachineSpace dual){
		super(drawArea,dual);
		machine = new Machine(3,drawArea.getSize());
		try{
			while(true) machine.moveCenter(machine.center.x,machine.center.y+1);
		}catch (MachineException e){
			try{
				machine.moveCenter(machine.center.x,machine.center.y-1);
			}catch(MachineException ex){}
		}
		alpha = Geomtry.getAngle(machine.center,machine.anchors[2]);
		angles[0] = alpha;
		dAlpha = 0.005;
	}
	public void redraw(Graphics g){
		Point[] anchors = machine.anchors;
		Point[] joints = machine.joints;
		Point center = machine.center;
		for(int i=0;i<3;i++){
			g.setColor(Color.black);
			if(i<2){
				drawLine(g,anchors[i],joints[i]);
				drawLine(g,joints[i],center);
			}else drawLine(g,center,anchors[2]);
			g.setColor(Color.green);
			if(i<2)g.fillOval(joints[i].x-3,joints[i].y-3,6,6);
			else {
				Coordinate mid = Geomtry.getMidPoint(anchors[2],center,0.5);
				g.fillOval(mid.toPoint().x-3,mid.toPoint().y-3,6,6);
			}
			g.setColor(Color.red);
			primitives.geomtry.Geomtry.drawAnchor(g,anchors[i]);
		//	g.drawLine(anchors[i].x-3,anchors[i].y-3,anchors[i].x+3,anchors[i].y+3);
		//	g.drawLine(anchors[i].x+3,anchors[i].y-3,anchors[i].x-3,anchors[i].y+3);
		}
		g.setColor(Color.green);
		g.fillOval(center.x-3,center.y-3,6,6);
	}
	public void keyTyped(int key)throws MachineException{
			switch (key){
		//	case /*KeyEvent.VK_LEFT*/1:machine.rotateLeg(2,0.05);break;
		//	case /*KeyEvent.VK_RIGHT*/-1:machine.rotateLeg(2,-0.05);break;
			}
			alpha = alpha+dAlpha*(key);
			try{
				machine.rotateLeg(2,alpha);
			}catch(MachineException e){
				if (key>0) angles[2] = alpha;
				else angles[1] = alpha;
				throw e;
			}

			
	}
	public void mouseClicked(int x,int y){
		Point clicked = new Point(x,y);
		if (Geomtry.distance(clicked,machine.anchors[0])<Geomtry.distance(clicked,machine.anchors[1]))
			machine.state[0]=machine.state[0]*(-1);
		else
			machine.state[1]=machine.state[1]*(-1);
	}
		
}