package primitives.machines;
import primitives.geomtry.*;
import java.awt.*;
/**
* Class used to control the motion of a 2-arms machine.
* Used by the TwoArmsSpaceDemo applet.
*@author Dori Eldar
*@see TwoArmsSpaceDemo
*/
public class TwoArmsMachine extends NarmsMachine{
	/**
	*The limit angles of motion [should be private]
	*/
	public double[] angles;
	/**
	*initializes the machines and checks the limit angles of its motion.
	*@param d the size of the rectangle the machine should be drawn in.
	*@param ratio see <a href="Machine.html#Machine">Machine</a>
	*@param i the arm to rotate 0 or 1.
	*/
	public TwoArmsMachine(Dimension d,double ratio,int i){
		super(d,2,ratio);
		angles = new double[2];
		for(int j=0;j<2;j++)
			try{
				while(true) rotateJoint(i,(-1+j*2)*0.01);
			}catch(MachineException e){
				angles[j] = Geomtry.getAngle(dAnchors[i],dJoints[i]);
				j++;
			}
	}
	/**
	* rotates the central joint relative to a given periferial joint.
	*@param i the relative joint to use.
	*@param dalpha the amount in radians to rotate.
	*@exception MachineException if the rotation is nt pysically possible.
	*@see Machine#rotateJoint
	*/
	public void rotateJoint(int i,double dalpha) throws MachineException{
		super.rotateJoint(dAnchors[i],dJoints[i],dalpha);
		dCenter = Geomtry.getMidPoint(dAnchors[1-i],dJoints[i],
			barLength/Geomtry.distance(dJoints[i],dAnchors[1-i]));
		try{
			dJoints[i-1] = Geomtry.getTriPointEx(dCenter,barLength,dAnchors[1-i],barLength,dJoints[1-i],dAnchors[i]);
			
		}catch(ArithmeticException e){
			dJoints[i-1] = Geomtry.getMidPoint(dCenter,dAnchors[i-1],0.5);
			throw new MachineException("reached end of arc");
		}
 	}
	/**
	* draws the machine using a specified graphic context.
	*@param g the graphic context to draw to.
	*@see MachineListener
	*/
	 public void redraw(Graphics g){
		super.redraw(g);
		g.setColor(Color.red);
		Geomtry.drawJoint(g,joints[1]);
	}
	/**
	*@exception java.lang.Throwable .
	*/
	public void finalize() throws Throwable{
		angles = null;
		super.finalize();
	}
}