#include "Camera.hpp"
#include "Transform.hpp"
#include "../ui/ComponentRegistration.hpp"
#include "../ui/CameraEditor.hpp"
#include "../systems/CameraSystem.hpp"

// Register Camera component
REGISTER_COMPONENT("Camera", CameraComponent, CameraEditor)
{
	registry.registerComponent<CameraComponent>(
		"Camera",
		std::make_unique<CameraEditor>(sceneMgr, renderWindow),
		// Adder
		[sceneMgr](flecs::entity e) {
			if (!e.has<CameraComponent>()) {
				// Camera requires Transform
				if (!e.has<TransformComponent>()) {
					// Auto-add transform if missing
					TransformComponent transform;
					transform.node = sceneMgr->getRootSceneNode()->createChildSceneNode();
					e.set<TransformComponent>(transform);
				}
				e.set<CameraComponent>({});
			}
		},
		// Remover
		[sceneMgr](flecs::entity e) {
			if (e.has<CameraComponent>()) {
				auto& camera = e.get_mut<CameraComponent>();
				// Clean up Ogre camera and preview resources
				if (camera.camera) {
					// Clean up preview
					if (camera.previewTarget) {
						camera.previewTarget->removeAllListeners();
					}
					if (camera.previewTexture) {
						Ogre::TextureManager::getSingleton().remove(
							camera.previewTexture->getName());
					}
					
					// Detach and destroy camera
					Ogre::SceneNode* parent = camera.camera->getParentSceneNode();
					if (parent) {
						parent->detachObject(camera.camera);
					}
					sceneMgr->destroyCamera(camera.camera);
					camera.camera = nullptr;
				}
				e.remove<CameraComponent>();
			}
		}
	);
}
