#include "core.h"
#include "game_ui.h"
#include "game_lua_help.h"
#include "texturesmanager.h"

#include <ImGui.h>

using namespace LuaPlus;

uint32_t ColorFromLua(const LuaObject& color)
{
	SDL_assert_always(color.IsTable());

	float r = color[1].ToNumber();
	float g = color[2].ToNumber();
	float b = color[3].ToNumber();
	float a = color[4].ToNumber();

	return ImGui::ColorConvertFloat4ToU32(ImVec4(r, g, b, a));
}

void uiDrawText(const char* text, float x, float y, const LuaObject& color)
{
	ImGui::GetBackgroundDrawList()->AddText(ImVec2(x, y), ColorFromLua(color), text);
}

void uiDrawRect(float x, float y, float w, float h,  const LuaObject& color)
{
	ImGui::GetBackgroundDrawList()->AddRectFilled(ImVec2(x, y), ImVec2(w, h), ColorFromLua(color));
}

void uiDrawImage(const char* filename, float x, float y, float w, float h, const LuaObject& color)
{
	ImTextureID texture = (ImTextureID)g_texturesManager->LoadTexture2D(filename);
	ImGui::GetBackgroundDrawList()->AddImage(texture, ImVec2(x, y), ImVec2(w, h), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), ColorFromLua(color));
}

int uiGetDisplaySize(LuaState* state)
{
	state->PushNumber(ImGui::GetIO().DisplaySize.x);
	state->PushNumber(ImGui::GetIO().DisplaySize.y);
	return 2;
}

int uiGetMousePos(LuaState* state)
{
	state->PushNumber(ImGui::GetIO().MousePos.x);
	state->PushNumber(ImGui::GetIO().MousePos.y);
	return 2;
}

int uiCalcTextWidth(LuaState* state)
{
	LuaStack stack(state);
	SDL_assert_always(stack[1].IsString());

	state->PushNumber(ImGui::CalcTextSize(stack[1].GetString()).x);

	return 1;
}

void registerEngineUI()
{
	LuaObject uiTable = GetLuaState().GetGlobals().CreateTable("ui");
	uiTable.RegisterDirect("draw_text", &uiDrawText);
	uiTable.RegisterDirect("draw_rect", &uiDrawRect);
	uiTable.RegisterDirect("draw_image", &uiDrawImage);
	uiTable.Register("get_display_size", &uiGetDisplaySize);
	uiTable.Register("get_mouse_pos", &uiGetMousePos);
	uiTable.Register("calc_text_width", &uiCalcTextWidth);
}

void gameRenderUI()
{
	LuaObject renderFunction = GetLuaState().GetGlobal("game_hud_draw");

	LuaFunctionVoid function = renderFunction;
	function();
}
