#include "CharacterSpawnerEditor.hpp"
#include "../systems/CharacterRegistry.hpp"
#include <imgui.h>

CharacterSpawnerEditor::CharacterSpawnerEditor(Ogre::SceneManager *sceneMgr)
	: m_sceneMgr(sceneMgr)
{
	(void)m_sceneMgr;
}

bool CharacterSpawnerEditor::renderComponent(
	flecs::entity entity, CharacterSpawnerComponent &spawner)
{
	(void)entity;
	bool modified = false;

	if (ImGui::CollapsingHeader("Character Spawner",
				    ImGuiTreeNodeFlags_DefaultOpen)) {
		ImGui::Indent();

		int registryId = static_cast<int>(spawner.registryId);
		if (ImGui::InputInt("Registry ID", &registryId)) {
			if (registryId >= 0) {
				spawner.registryId =
					static_cast<uint64_t>(registryId);
				modified = true;
			}
		}
		if (ImGui::IsItemHovered()) {
			ImGui::SetTooltip(
				"Character registry ID of the character to spawn");
		}

		const CharacterRegistry::CharacterRecord *rec =
			CharacterRegistry::getSingleton().findCharacter(
				spawner.registryId);
		if (rec) {
			ImGui::TextDisabled("Character: %s %s",
					    rec->firstName.c_str(),
					    rec->lastName.c_str());
		} else if (spawner.registryId != 0) {
			ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f),
					   "No character with this registry ID");
		}

		float spawnDist = std::sqrt(spawner.spawnDistanceSq);
		if (ImGui::DragFloat("Spawn Distance", &spawnDist, 1.0f,
				     0.0f, 10000.0f)) {
			spawner.spawnDistanceSq = spawnDist * spawnDist;
			modified = true;
		}

		float despawnDist = std::sqrt(spawner.despawnDistanceSq);
		if (ImGui::DragFloat("Despawn Distance", &despawnDist, 1.0f,
				     0.0f, 10000.0f)) {
			spawner.despawnDistanceSq = despawnDist * despawnDist;
			modified = true;
		}

		if (spawner.spawnDistanceSq > spawner.despawnDistanceSq) {
			ImGui::TextColored(
				ImVec4(1.0f, 0.4f, 0.4f, 1.0f),
				"Spawn distance is greater than despawn distance");
		}

		ImGui::Unindent();
	}

	return modified;
}
