package primitives.machines;
import primitives.geomtry.*;
import java.awt.*;
/**
* A missleading name for this class. A class originaly used to draw a 2 legs machine
* was generelized to manipulate a machine with one anchor and a series of connected 
* joints starting from the anchor.
*@see TwoLegDemo
*@see TwoLegSpaceDemo
*@author Dori Eldar
*/
public class TwolegsMachine extends Machine{
		/**
		* Numner of legs in the machine.
		* [should be private]
		*/
		public int legs;
		/**
		* A list of current angles between adjacent joints.
		* Used to preform rotations.
		*@see #rotateJoint
		*/
		double[] angles;
		/**
		* A list of the machine's rigid bars' lenghts.
		*/
		double[] distances;
		/**
		*Initializes a machine with a given number of legs.
		*@param d the size of the rectangle to draw the machine in.
		*@param legs the number of legs of the machine.
		*/
		public TwolegsMachine(Dimension d,int legs){
		super(legs,1,d);
		this.legs = legs;
		barLength = Math.min(d.width,d.height)/(legs*2)-4;
		dAnchors[0] = new Coordinate(d.width/2,d.height/2);
		updatePoints(dAnchors,anchors);
		integrizeAnchors();
		for(int i=0;i<legs;i++)
			dJoints[i] = new Coordinate(anchors[0].x,anchors[0].y+barLength*(i+1));
		angles = new double[legs];
		distances = new double[legs];
	}
	/**
	*Draws the machine.
	*@param g the grapic context to draw to.
	*@see MachineListener
	*/
	public void redraw(Graphics g){
		updatePoints(dJoints,joints);
		g.setColor(Color.black);
		for(int i=0;i<legs-1;i++)
			drawLine(g,joints[i],joints[i+1]);
		drawLine(g,anchors[0],joints[0]);
		super.redraw(g);
		
	}
	
	/**
	*Rotates the machine by physically rotating the specified joint.
	*@param leg rotate the machine starting from this joint.
	*@param dalpha the amount in radians to rotate the specified joint.
	*@see Machine#rotateJoint
	*/
	public void rotateJoint(int leg, double dalpha){
		Coordinate startPoint;
		Coordinate endPoint;
		switch(leg){
		case 0:
			startPoint = dAnchors[0];
			endPoint = dJoints[0];
			leg++;
			break;	 
		default:startPoint = dJoints[leg-1];
			endPoint = dJoints[leg];
		}
		for(int i=leg;i<legs;i++){
				angles[i] = Geomtry.getAngle(startPoint,dJoints[i]);
				distances[i]  = Geomtry.distance(startPoint,dJoints[i]);
		}
		super.rotateJoint(startPoint,endPoint,dalpha);
			for(int i=leg;i<legs;i++)
				dJoints[i] = Geomtry.getPointByVector(startPoint,distances[i],dalpha+angles[i]);
		 
	}
}