#include "EventHandlerEditor.hpp"
#include "../components/ActionDatabase.hpp"
#include <imgui.h>

static ActionDatabase *findDatabase(flecs::entity entity)
{
	(void)entity;
	return ActionDatabase::getSingletonPtr();
}

bool EventHandlerEditor::renderComponent(flecs::entity entity,
					 EventHandlerComponent &handler)
{
	bool modified = false;
	ImGui::PushID("EventHandler");

	char eventBuf[256];
	snprintf(eventBuf, sizeof(eventBuf), "%s", handler.eventName.c_str());
	if (ImGui::InputText("Event Name", eventBuf, sizeof(eventBuf))) {
		handler.eventName = eventBuf;
		modified = true;
	}

	if (ImGui::Checkbox("Enabled", &handler.enabled))
		modified = true;

	// Action selection from database
	ActionDatabase *db = findDatabase(entity);
	if (db && !db->actions.empty()) {
		int selected = -1;
		std::vector<const char *> names;
		for (size_t i = 0; i < db->actions.size(); i++) {
			names.push_back(db->actions[i].name.c_str());
			if (handler.actionName == db->actions[i].name)
				selected = static_cast<int>(i);
		}
		if (ImGui::Combo("Action", &selected, names.data(),
				 static_cast<int>(names.size()))) {
			if (selected >= 0 &&
			    selected < static_cast<int>(names.size()))
				handler.actionName = names[selected];
			modified = true;
		}
	} else {
		ImGui::TextDisabled("No actions in database");
		char actionBuf[256];
		snprintf(actionBuf, sizeof(actionBuf), "%s",
			 handler.actionName.c_str());
		if (ImGui::InputText("Action Name", actionBuf,
				    sizeof(actionBuf))) {
			handler.actionName = actionBuf;
			modified = true;
		}
	}

	ImGui::PopID();
	return modified;
}
