#include "gameplay/ai.h"
#include "gameplay/gameactor.h"

#include "utility/raycaster.h"
#include "utility/script.h"


AI::AI(const std::shared_ptr<GameActor>& actor, const std::shared_ptr<Raycaster>& raycaster)
	: actor(actor), raycaster(raycaster), state(AIState::Idle)
{}

void AI::attachBehaviourScript(const std::shared_ptr<AIScript>& behaviour)
{
	// passing out instance of raycaster this Ai into our scripting api
	// pay special attention each ai script has control of only their own instance of ai!
	this->behaviour = behaviour;
	this->behaviour->lua["raycaster"] = raycaster;
	this->behaviour->lua["ai"] = std::shared_ptr<AI>(this);
}

void AI::update()
{
	try {
		switch (state)
		{
		case AIState::Idle:
			if (behaviour && behaviour->lua["idle"].valid())
			{
				auto result = behaviour->lua["idle"](actor, target);
				if (!result.valid())
				{
					sol::error err = result;
					std::cerr << "lua error: " << err.what() << std::endl;
				}
			}
			break;
		case AIState::Patrol:
			if (behaviour && behaviour->lua["patrol"].valid())
			{
				auto result = behaviour->lua["patrol"](actor, target);
				if (!result.valid())
				{
					sol::error err = result;
					std::cerr << "lua error: " << err.what() << std::endl;
				}
			}
			break;
		case AIState::Alert:
			if (behaviour && behaviour->lua["alert"].valid())
			{
				auto result = behaviour->lua["alert"](actor, target);
				if (!result.valid())
				{
					sol::error err = result;
					std::cerr << "lua error: " << err.what() << std::endl;
				}
			}
			break;
		}
		behaviour->lua.collect_gc();
	}
	catch (const std::exception& e) {
		std::cerr << "Error during AI update: " << e.what() << std::endl;
		state = AIState::Idle;
	}
}