#include "core.h"
#include "game_world_objects.h"
#include "debugrender.h"
#include "scenemanager.h" // BAD!

bool g_debugDrawLights = false;

REGISTER_ENTITY(Light);

Light::Light()
{
	//m_dlight = nullptr;
	m_dlight = DLightManager::GetInstance()->AllocLight();
}

Light::~Light()
{
}

void Light::Render()
{
	if (!m_dlight)
		return;

	m_dlight->position = m_position;

	if (g_debugDrawLights)
	{
		g_debugRender->DrawAxis(m_dlight->position);
		g_debugRender->DrawSphere(m_dlight->position, m_dlight->radius, m_dlight->color);
	}
}

void Light::RegisterFunctions()
{
	m_luaObject.Register("set_color", *this, &Light::Lua_SetColor);
	m_luaObject.Register("get_color", *this, &Light::Lua_GetColor);

	m_luaObject.Register("set_radius", *this, &Light::Lua_SetRadius);
	m_luaObject.Register("get_radius", *this, &Light::Lua_GetRadius);
}

void Light::InitFromXML(const pugi::xml_node& node)
{
	//m_dlight = DLightManager::GetInstance()->AllocLight();
	SDL_assert_always(m_dlight);
	m_dlight->position = m_position;

	pugi::xml_node color = node.child("Color");
	if (color)
	{
		m_dlight->color.r = color.attribute("r").as_float();
		m_dlight->color.g = color.attribute("g").as_float();
		m_dlight->color.b = color.attribute("b").as_float();
	}

	pugi::xml_node radius = node.child("Radius");
	if (radius)
	{
		m_dlight->radius = radius.attribute("value").as_float();
	}
}

int Light::Lua_SetColor(LuaPlus::LuaState* state)
{
	SDL_assert_always(m_dlight);

	LuaPlus::LuaStack stack(state);
	m_dlight->color.r = stack[2].GetFloat();
	m_dlight->color.g = stack[3].GetFloat();
	m_dlight->color.b = stack[4].GetFloat();

	return 0;
}

int Light::Lua_GetColor(LuaPlus::LuaState* state)
{
	SDL_assert_always(m_dlight);

	state->PushNumber(m_dlight->color.r);
	state->PushNumber(m_dlight->color.g);
	state->PushNumber(m_dlight->color.b);

	return 3;
}

int Light::Lua_SetRadius(LuaPlus::LuaState* state)
{
	SDL_assert_always(m_dlight);

	LuaPlus::LuaStack stack(state);
	m_dlight->radius = stack[2].GetFloat();

	return 0;
}

int Light::Lua_GetRadius(LuaPlus::LuaState* state)
{
	SDL_assert_always(m_dlight);

	state->PushNumber(m_dlight->radius);

	return 1;
}
