#include "Shared/RobotInfo.h"
#if defined(TGT_HAS_ARMS) && defined(TGT_HAS_HEAD)

#include "Behaviors/StateMachine.h"
#include "DualCoding/DualCoding.h"
#include "Planners/RRT/RRTPlanner.h"
#include "Sound/SoundManager.h"
#include "local/DeviceDrivers/MirageComm.h"

using namespace std;
using namespace DualCoding;

class ArmPathPlan1 : public VisualRoutinesStateNode {
public:

	class LookDown : public HeadPointerNode {
	public:
		LookDown() : HeadPointerNode("LookDown") {}

		virtual void doStart() {
			getMC()->setJoints(0, -0.167f, -1.2f);
		}
	};

	class FindObstacles : public MapBuilderNode {
	public:
		FindObstacles() : MapBuilderNode("FindObstacles",MapBuilderRequest::localMap) {}

		virtual void doStart() {
			mapreq.addObjectColor(ellipseDataType, "pink");
			mapreq.addObjectColor(ellipseDataType, "blue");
			mapreq.addObjectColor(ellipseDataType, "green");
		}
	};
	
	class Simulate : public StateNode {
		ionetstream net;
	public:
		Simulate() : StateNode(), net() {}
		
		virtual void doStart() {
			// create some obstacles at known locations for accurate testing
			localShS.clear();
			float radius = 50;
			NEW_SHAPE(ob1, EllipseData, new EllipseData(localShS,DualCoding::Point(300,100),radius,radius));
			//NEW_SHAPE(ob2, EllipseData, new EllipseData(localShS,DualCoding::Point(225,-200),radius,radius));
			
			// display these in mirage...
			MirageComm comm(net);
			std::vector<DualCoding::Shape<EllipseData> > obs = select_type<EllipseData>(localShS);
			for(size_t i=0; i<obs.size(); ++i) {
				float x = obs[i]->getCentroid().coordX(), y = obs[i]->getCentroid().coordY();
				float r = obs[i]->getSemimajor();
				
				std::stringstream ss;
				ss << "ArmPathPlanObstacles" << i;
				comm.setName(ss.str());
				KinematicJoint * kj = new KinematicJoint;
				comm.setKinematics(kj);
				kj->mass=1;
				kj->collisionModel = "Cylinder";
				kj->collisionModelScale[0] = kj->collisionModelScale[1] = kj->collisionModelScale[2] = r*2;
				comm.setPosition(x,y,r);
			}
		}
	};

	class ExecutePath : public DynamicMotionSequenceNode {
	public:
		ExecutePath() : DynamicMotionSequenceNode("ExecutePath") {}

		virtual void doStart() {
			vector<PlannerObstacle*> obstacles;
			NEW_SHAPEVEC(ellipses, EllipseData, select_type<EllipseData>(localShS))
			SHAPEVEC_ITERATE(ellipses, EllipseData, e)
				CircularObstacle * ob = new CircularObstacle();
				ob->center = fmat::pack(e->getCentroid().coordX(), e->getCentroid().coordY());
				ob->radius = max(e->getSemimajor(), e->getSemiminor()) * 1.1f; // add 10% margin around obstacles
				cout<<"Obstacle at "<<ob->center[0]<<","<<ob->center[1]<<" with radius "<<ob->radius<<endl;
				obstacles.push_back(ob);
			END_ITERATE;
			
			unsigned int const numJoints = 3;
			RRTStateVector stateVec(6000, numJoints);
			
			RRTPlanner rrtp(stateVec, GripperFrameOffset, numJoints, 1000, 0.0001f, (float)M_PI/60, (float)M_PI/120, NULL);
			/* Generate the instance of the planner
				 stateVec		- RRTStateVector* for where to store the states used in planning
				 GripperFrameOffset	- The end effector you want to use
				 numJoints (optional)	- How many joints down the kinematic chain you want to go
				 1000 (optional)		- The maximum number of iterations you want the planner to go through
				 0.4f (optional)		- The allowed error between two states to call them "equal". Make lower for better results, but may not converge
				 M_PI/30.0f (optional)	- The largest change each joint can change by between states
				 M_PI/120.0f (optional)	- The largest change each joint can change by during an interpolation check (finer grain so it won't miss any obstacles)
			*/
			
			RRTStateDef startSt(numJoints), endSt(numJoints);
			for(unsigned int i = 0; i < numJoints; i++)
				startSt[i] = state->outputs[ArmShoulderOffset + i];
			endSt[0] = startSt[0] > 0 ? -1.2f : 1.4f;
			endSt[1] = 0;
			endSt[2] = 0;

			const KinematicJoint* gripper = kine->getKinematicJoint(GripperFrameOffset);
			fmat::Column<3> where = gripper->getWorldPosition();
			NEW_SHAPE(tgt, PointData, new PointData(localShS, DualCoding::Point(where[0], where[1], where[2])));


			RRTPath path;
			if ( !rrtp.Plan(path, startSt, endSt, &obstacles) ) {
				postStateSignal<bool>(0);
				return;
			}

			getMC()->clear();
			generatePostures(path);
			getMC()->play();
		}

		void generatePostures(const RRTPath& path) {
			cout << "Making postures..." << endl;
			getMC()->setTime(1000);
			for(unsigned int i = 0; i < path.size(); i++) {
				cout << "Step " << i << "   ";
				for(unsigned int j = 0; j < path[i].size(); j++) {
					cout << "  " << j << ": " << path[i][j];
					getMC()->setOutputCmd(ArmOffset+j, path[i][j]);
				}
				cout << endl;
				getMC()->advanceTime(200);
			}
		}
	};


	ArmPathPlan1() : VisualRoutinesStateNode("ArmPathPlan1") {}

	virtual void doStart() {
		std::cout << "Place an obstacle in front of the arm and press the green button or send a 'go' text message to tell it to move." << std::endl;
	}

	virtual void setup() {
#statemachine
		startnode: LookDown() =C=>
			loop: SpeechNode("ready") =TM("go")=>
				obs: FindObstacles() =MAP=>
					exec: ExecutePath() =C=> loop
		
		loop =TM("sim")=> Simulate() =N=> exec
		
		exec =S<bool>=> SpeechNode("No path found.") =T(2500)=> loop
#endstatemachine
		
#ifdef TGT_HAS_BUTTONS
		// because stateparser can't handle ifdef's within statemachine...
		// manual expansion of loop =B(GreenButOffset)=> obs
		loop->addTransition(new EventTrans(obs,EventBase::buttonEGID,RobotInfo::GreenButOffset,EventBase::activateETID));
#endif
	}

};

REGISTER_BEHAVIOR_MENU(ArmPathPlan1,DEFAULT_TK_MENU"/Kinematics Demos");

#endif
