#include "NavMeshEditor.hpp"
#include "../systems/NavMeshSystem.hpp"
#include <imgui.h>
#include <OgreLogManager.h>

NavMeshEditor::NavMeshEditor() = default;

bool NavMeshEditor::renderComponent(flecs::entity entity,
				    NavMeshComponent &comp)
{
	bool modified = false;
	ImGui::PushID("NavMesh");

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

	if (ImGui::Checkbox("Debug Draw", &comp.debugDraw))
		modified = true;

	renderParams(comp);

	if (ImGui::Button("Rebuild NavMesh")) {
		comp.dirty = true;
		modified = true;
	}

	if (comp.dirty) {
		ImGui::SameLine();
		ImGui::TextDisabled("(dirty)");
	}

	renderPathTester(entity);

	ImGui::PopID();
	return modified;
}

void NavMeshEditor::renderParams(NavMeshComponent &comp)
{
	if (ImGui::TreeNode("Build Parameters")) {
		ImGui::InputFloat("Cell Size", &comp.cellSize, 0.05f,
				  0.0f, "%.2f");
		ImGui::InputFloat("Cell Height", &comp.cellHeight,
				  0.05f, 0.0f, "%.2f");
		ImGui::InputFloat("Agent Height", &comp.agentHeight,
				  0.1f, 0.0f, "%.2f");
		ImGui::InputFloat("Agent Radius", &comp.agentRadius,
				  0.1f, 0.0f, "%.2f");
		ImGui::InputFloat("Agent Max Climb",
				  &comp.agentMaxClimb, 0.1f,
				  0.0f, "%.2f");
		ImGui::InputFloat("Agent Max Slope",
				  &comp.agentMaxSlope, 1.0f,
				  0.0f, "%.1f");
		ImGui::InputFloat("Edge Max Len",
				  &comp.edgeMaxLen, 1.0f,
				  0.0f, "%.1f");
		ImGui::InputFloat("Edge Max Error",
				  &comp.edgeMaxError, 0.1f,
				  0.0f, "%.2f");
		ImGui::InputFloat("Region Min Size",
				  &comp.regionMinSize, 1.0f,
				  0.0f, "%.1f");
		ImGui::InputFloat("Region Merge Size",
				  &comp.regionMergeSize, 1.0f,
				  0.0f, "%.1f");
		ImGui::InputInt("Tile Size", &comp.tileSize);
		if (comp.tileSize < 16)
			comp.tileSize = 16;
		if (comp.tileSize > 128)
			comp.tileSize = 128;
		ImGui::TreePop();
	}
}

void NavMeshEditor::renderPathTester(flecs::entity navmeshEntity)
{
	if (!ImGui::TreeNode("Path Tester"))
		return;

	ImGui::InputFloat3("Start", m_startPos);
	ImGui::InputFloat3("End", m_endPos);

	if (ImGui::Button("Find Path")) {
		NavMeshSystem *sys = NavMeshSystem::getInstance();
		if (sys) {
			m_pathValid = sys->findPath(
			    navmeshEntity,
			    Ogre::Vector3(m_startPos[0], m_startPos[1],
					  m_startPos[2]),
			    Ogre::Vector3(m_endPos[0], m_endPos[1],
					  m_endPos[2]),
			    m_lastPath);
		} else {
			m_pathValid = false;
			m_lastPath.clear();
		}
	}

	if (m_pathValid) {
		ImGui::Text("Path found (%zu points):",
			    m_lastPath.size());
		for (size_t i = 0; i < m_lastPath.size(); i++) {
			ImGui::Text("  [%zu] (%.2f, %.2f, %.2f)", i,
				    m_lastPath[i].x, m_lastPath[i].y,
				    m_lastPath[i].z);
		}
	} else {
		ImGui::TextDisabled("No path found yet");
	}

	ImGui::TreePop();
}
