#include "SmartObjectEditor.hpp"
#include <imgui.h>

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

bool SmartObjectEditor::renderComponent(flecs::entity entity,
					SmartObjectComponent &so)
{
	bool modified = false;
	ImGui::PushID("SmartObject");

	ImGui::Text("Smart Object Settings");
	ImGui::Separator();

	if (ImGui::DragFloat("Radius", &so.radius, 0.1f, 0.1f, 100.0f,
			     "%.1f")) {
		if (so.radius < 0.1f)
			so.radius = 0.1f;
		modified = true;
	}
	ImGui::SameLine();
	ImGui::TextDisabled("(XZ interaction distance)");

	if (ImGui::DragFloat("Height", &so.height, 0.1f, 0.1f, 100.0f,
			     "%.1f")) {
		if (so.height < 0.1f)
			so.height = 0.1f;
		modified = true;
	}
	ImGui::SameLine();
	ImGui::TextDisabled("(Y interaction threshold)");

	ImGui::Separator();
	ImGui::Text("Actions:");
	ImGui::Indent();

	// List currently selected actions
	for (size_t i = 0; i < so.actionNames.size(); i++) {
		ImGui::PushID(static_cast<int>(i));
		ImGui::Text("%s", so.actionNames[i].c_str());
		ImGui::SameLine();
		if (ImGui::SmallButton("X")) {
			so.actionNames.erase(so.actionNames.begin() + i);
			modified = true;
			ImGui::PopID();
			break;
		}
		ImGui::PopID();
	}

	// Add action from database
	ActionDatabase *db = findDatabase(entity);
	if (db && !db->actions.empty()) {
		ImGui::Separator();
		ImGui::Text("Add action:");
		static int selectedAction = -1;

		// Build list of action names not already selected
		std::vector<const char *> availableNames;
		std::vector<Ogre::String> availableNamesStorage;
		for (const auto &action : db->actions) {
			bool alreadySelected = false;
			for (const auto &selected : so.actionNames) {
				if (selected == action.name) {
					alreadySelected = true;
					break;
				}
			}
			if (!alreadySelected) {
				availableNamesStorage.push_back(action.name);
				availableNames.push_back(
					availableNamesStorage.back().c_str());
			}
		}

		if (!availableNames.empty()) {
			if (selectedAction >= (int)availableNames.size())
				selectedAction = 0;
			if (ImGui::Combo("##actionSelect", &selectedAction,
					 availableNames.data(),
					 (int)availableNames.size())) {
				// Selection changed
			}
			ImGui::SameLine();
			if (ImGui::Button("Add")) {
				if (selectedAction >= 0 &&
				    selectedAction <
					    (int)availableNames.size()) {
					so.actionNames.push_back(
						availableNamesStorage
							[selectedAction]);
					modified = true;
				}
			}
		} else {
			ImGui::TextDisabled("All actions already selected");
		}
	} else {
		ImGui::TextDisabled("No actions in database");
	}

	ImGui::Unindent();
	ImGui::PopID();
	return modified;
}
