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

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

bool ActuatorEditor::renderComponent(flecs::entity entity,
				     ActuatorComponent &actuator)
{
	bool modified = false;
	ImGui::PushID("Actuator");

	ImGui::Text("Actuator Settings");
	ImGui::Separator();

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

	if (ImGui::DragFloat("Height", &actuator.height, 0.1f, 0.1f, 100.0f,
			     "%.1f")) {
		if (actuator.height < 0.1f)
			actuator.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 < actuator.actionNames.size(); i++) {
		ImGui::PushID(static_cast<int>(i));
		ImGui::Text("%s", actuator.actionNames[i].c_str());
		ImGui::SameLine();
		if (ImGui::SmallButton("X")) {
			actuator.actionNames.erase(
				actuator.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;

		std::vector<const char *> availableNames;
		std::vector<Ogre::String> availableNamesStorage;
		for (const auto &action : db->actions) {
			bool alreadySelected = false;
			for (const auto &selected : actuator.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())) {
			}
			ImGui::SameLine();
			if (ImGui::Button("Add")) {
				if (selectedAction >= 0 &&
				    selectedAction < (int)availableNames.size()) {
					actuator.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;
}
