#include "stdafx.h"
#include "Behaviour.h"
#include "BehaviourTree.h"
#include <IExamInterface.h>

namespace BT_Action
{
	BT::State FindAHouse(Blackboard* blackboardPtr) {
		IExamInterface* interfacePtr{};
		blackboardPtr->GetData("Interface", interfacePtr);

		const Elite::Vector2 worldDimensions{ interfacePtr->World_GetInfo().Dimensions };

		std::random_device rd; // obtain a random number from hardware
		std::mt19937 seed(rd()); // seed the generator
		std::uniform_int_distribution<> range(-worldDimensions.x, worldDimensions.x); // define the range

		const Elite::Vector2 randomLocation(range(seed), range(seed));
		const Elite::Vector2 target = interfacePtr->NavMesh_GetClosestPathPoint(randomLocation);

		if (randomLocation != target) {
			blackboardPtr->ChangeData("Target", randomLocation);

			std::cout << "Data send " << randomLocation << "\n";

			return BT::State::Success;
		}

		return BT::State::Failure;
	}

	BT::State GoToTarget(Blackboard* blackboardPtr) {
		IExamInterface* interfacePtr{};
		Elite::Vector2 target{};
		SteeringPlugin_Output steering{};

		blackboardPtr->GetData("Interface", interfacePtr);
		blackboardPtr->GetData("Target", target);
		blackboardPtr->GetData("Steering", steering);

		std::cout << "target received " << target << "\n";

		const auto agentInfo = interfacePtr->Agent_GetInfo();

		const auto nextTargetPos = interfacePtr->NavMesh_GetClosestPathPoint(target);

		steering.LinearVelocity = nextTargetPos - agentInfo.Position;
		steering.LinearVelocity.Normalize();
		steering.LinearVelocity *= agentInfo.MaxLinearSpeed;

		if (Distance(nextTargetPos, agentInfo.Position) < 2.f) {
			steering.LinearVelocity = Elite::ZeroVector2;

			std::cout << "target reached at " << target << "\n";

			return BT::State::Success;
		}

		blackboardPtr->ChangeData("Steering", steering);

		return BT::State::Running;
	}
}