#include "Behaviors/StateMachine.h"

#include "Behaviors/Nodes/PostureNode.h"
#include "Behaviors/Transitions/EventTrans.h"
#include "Motion/MotionPtr.h"
#include "Shared/RobotInfo.h"





#include "Behaviors/StateMachine.h"
#include "Behaviors/Demos/Navigation/PilotDemo.h"

#define PI (3.14159265)
#define FOODX (780+300+300-390)
#define FOODY (400)
#define FOODA (PI/2)
#define HAND WristRotateOffset

$nodeclass GetSnackMod: PilotDemo {
    $provide std::string boxColor;
    enum outcome {gripping, failure};

    
    virtual void buildMap() {
        //April Tags
		NEW_SHAPE(tag1, AprilTagData,new AprilTagData(worldShS, Point(0-390+2750-294-15,0-400+30/2+1,177.8), AprilTags::TagDetection(1) ));
		NEW_SHAPE(tag3, AprilTagData,new AprilTagData(worldShS, Point(0-390+147+15,0-400+30/2+1,177.8), AprilTags::TagDetection(3) ));
		NEW_SHAPE(tag2, AprilTagData,new AprilTagData(worldShS, Point(0-390+2750/2,0-400+30/2+1,177.8), AprilTags::TagDetection(2) ));
		NEW_SHAPE(tag0, AprilTagData,new AprilTagData(worldShS, Point(0-390+2750-15-0.5,0-400+367,177.8), AprilTags::TagDetection(0) ));
		NEW_SHAPE(tag4, AprilTagData,new AprilTagData(worldShS, Point(0-390+15+0.5,0-400+367,177.8), AprilTags::TagDetection(4) ));
		NEW_SHAPE(tag12, AprilTagData,new AprilTagData(worldShS, Point(0-390+780+300/2,800-400-15,177.8), AprilTags::TagDetection(12) ));
		NEW_SHAPE(tag17, AprilTagData,new AprilTagData(worldShS, Point(0-390+780+300+600+390/2,800-400-15,177.8), AprilTags::TagDetection(17) ));
		NEW_SHAPE(tag18, AprilTagData,new AprilTagData(worldShS, Point(0-390+780+300+600/2,1700-400-15+80,177.8), AprilTags::TagDetection(18) ));

		//Maze
		std::vector<Point> E;		
		E.push_back(Point(2750-390, 0-400, 0));
		E.push_back(Point(2750-390, 800-400, 0));
		E.push_back(Point(780+300+600-390, 800-400, 0));
		E.push_back(Point(780+300+600-390, 800+980-400, 0));
		E.push_back(Point(780+300-390, 800+980-400, 0));
		E.push_back(Point(780+300-390, 800-400, 0));
		E.push_back(Point(780-390, 800-400, 0));
		E.push_back(Point(780-390, 1700-400, 0));
		E.push_back(Point(0-390, 1700-400, 0));
		E.push_back(Point(0-390, 0-400, 0));
		NEW_SHAPE(worldBounds, PolygonData, new PolygonData(worldShS, E, true));
		worldBounds->setColor("blue");

		// Virtual points
		NEW_SHAPE(snacks, PointData, new PointData(worldShS, Point(990-100,100,0)));
		snacks->setObstacle(false);
		NEW_SHAPE(cobot, PointData, new PointData(worldShS, Point(0,0,0)));
		cobot->setObstacle(false);
	}
	
	$nodeclass Loc : PilotNode(PilotTypes::localize) : doStart {
	    //particleFilter->resetFilter();
		if (pilotreq.landmarks.size() == 0) {
			cout << "Adding Landmarks" << endl;
			GET_SHAPE(tag0, AprilTagData, worldShS);
			GET_SHAPE(tag1, AprilTagData, worldShS);
			GET_SHAPE(tag2, AprilTagData, worldShS);
			GET_SHAPE(tag3, AprilTagData, worldShS);
			GET_SHAPE(tag4, AprilTagData, worldShS);
			GET_SHAPE(tag12, AprilTagData, worldShS);
			GET_SHAPE(tag17, AprilTagData, worldShS);
			GET_SHAPE(tag18, AprilTagData, worldShS);

			pilotreq.landmarks.push_back(tag0);
			pilotreq.landmarks.push_back(tag1);
			pilotreq.landmarks.push_back(tag2);
			pilotreq.landmarks.push_back(tag3);
			pilotreq.landmarks.push_back(tag4);
			pilotreq.landmarks.push_back(tag12);
			pilotreq.landmarks.push_back(tag17);
			pilotreq.landmarks.push_back(tag18);
		}

		MapBuilderRequest* req = new MapBuilderRequest(MapBuilderRequest::localMap);
		req->setAprilTagFamily(16,5);

		pilotreq.landmarkExtractor = req;
	}
	
	
	
	
	
	
	
	
    $nodeclass Starter : PilotNode(PilotTypes::goToShape) : doStart {
        GET_SHAPE(snacks, PointData, worldShS);
		pilotreq.targetShape = snacks;
		cout << "=======> Starter: " << snacks->getCentroid().coordX() << "," << snacks->getCentroid().coordY() << endl;
		pilotreq.collisionAction = collisionIgnore;
    }
    
    $nodeclass Turner : PilotNode(PilotTypes::walk) : doStart {
        pilotreq.collisionAction = collisionIgnore;
        pilotreq.da = atan2(FOODY-theAgent->getCentroid().coordY(), FOODX-theAgent->getCentroid().coordX()) - theAgent->getOrientation();
    }
    
    $nodeclass FindSnacks : MapBuilderNode(MapBuilderRequest::worldMap) : doStart {
        NEW_SHAPE(food, PointData, new PointData(worldShS, Point(FOODX, FOODY, 0, allocentric)));
        mapreq.searchArea = food;

        mapreq.addObjectColor(blobDataType, "red");
        mapreq.addBlobOrientation("red",BlobData::pillar);
        mapreq.addObjectColor(blobDataType, "blue");
        mapreq.addBlobOrientation("blue",BlobData::pillar);
    }
    
    $nodeclass ArmMover : PostureNode : doStart {
        $reference GetSnackMod::boxColor;
        for(unsigned int off = ArmOffset; off < ArmOffset+NumArmJoints; off++)
            getMC()->setMaxSpeed(off, 0.3);
        
        NEW_SHAPEVEC(world_cans, BlobData, select_type<BlobData>(worldShS));
        SHAPEVEC_ITERATE(world_cans, BlobData, can){
            can->setObstacle(false);
        }END_ITERATE;
        
        NEW_SHAPEVEC(cans, BlobData, select_type<BlobData>(localShS));
        IsColor colortest(boxColor);
        int best_index = -1;
        float min_dist = 99999999; 
        int i = 0;
        SHAPEVEC_ITERATE(cans, BlobData, can){
            if (colortest(can)) {
                if (best_index < 0 || min_dist > theAgent->getCentroid().distanceFrom(can->getCentroid())) {
                    min_dist = theAgent->getCentroid().distanceFrom(can->getCentroid());
                    best_index = i;
                    cout << "Found better can (dist = " << min_dist << ")\n";
                }
            }
            i++;
        }END_ITERATE;
        if (best_index == -1) {
            cout << "Did not find a can!\n";
            while(1);
        }
        
        fmat::Column<3> target = fmat::pack(cans[best_index]->getCentroid().coordX(),cans[best_index]->getCentroid().coordY(),60);
        fmat::Quaternion sideGrip = fmat::Quaternion::aboutZ(M_PI/2);
        fmat::Quaternion overheadGrip = fmat::Quaternion::aboutY(-M_PI/2);
        
    	cout << "========> Reaching for " << target[0] << "," << target[1] << "," << target[2] << endl;
        bool solved = getMC()->solveLink(target, overheadGrip, GripperFrameOffset,
                                         fmat::ZERO3, fmat::Quaternion::IDENTITY);
        cout << "===========>    solved = " << solved << "    <================" << endl;
    }

    $nodeclass GoToCobot : PilotNode(PilotTypes::goToShape) : doStart {
        GET_SHAPE(cobot, PointData, worldShS);
		pilotreq.targetShape = cobot;
		cout << "=======> Starter: " << cobot->getCentroid().coordX() << "," << cobot->getCentroid().coordY() << endl;
		pilotreq.collisionAction = collisionIgnore;
    }
    
    $nodeclass Grab : PostureNode : doStart{
        getMC()->setOutputCmd(LeftFingerOffset, OutputCmd(-0.1));
        getMC()->setOutputCmd(RightFingerOffset, OutputCmd(0.1));
    }
    
    $nodeclass CheckPressure : PostureNode : doStart{
        if (state->outputs[LeftFingerOffset] == -0.1 ||
            state->outputs[RightFingerOffset] == 0.1)
            postStateSignal<outcome>(failure);
            
        postStateSignal<outcome>(gripping);
    }
    
    $nodeclass GoForRed : StateNode : doStart {
        $reference GetSnackMod::boxColor;
        cout << "Setting color to red.\n";
        boxColor = "red";
        cout << "Done setting color to red.\n";
    }
    
    $nodeclass GoForBlue : StateNode : doStart {
        $reference GetSnackMod::boxColor;
        cout << "Setting color to blue.\n";
        boxColor = "blue";
    }
    

    virtual void setup() {
        // We make the posture motion command here and supply it to the
		// PostureNode via setMC() so that it only has to be registered
		// with the MotionManager once. Registering and deregistering a
		// PostureMC inside a tight sensor loop is inefficient and leads
		// to crashes.
		MotionManager::MC_ID posturemc = addMotion(MotionPtr<PostureMC>());

        $statemachine {
            startdemo: DynamicMotionSequenceNode("arm_ready.mot") 
            checkpressure: CheckPressure[setMC(posturemc)]
            grab: Grab[setMC(posturemc)] =C=> checkpressure
            checkpressure =S<outcome>(failure)=> Loc =PILOT=> FindSnacks =C=> ArmMover =C=> grab
            checkpressure =S<outcome>(gripping)=> DynamicMotionSequenceNode("carrying.mot") =C=> GoToCobot =PILOT=> startdemo
            getit: Loc =PILOT=> Starter =PILOT=> Turner =PILOT=> FindSnacks =C=> DynamicMotionSequenceNode("ready_to_grab.mot") =C=> ArmMover =C=> grab
            startdemo =TM("red")=> GoForRed =N=> getit
            startdemo =TM("blue")=> GoForBlue =N=> getit
        }
    }

}


REGISTER_BEHAVIOR(GetSnackMod);
