#include "TriangleBuffer.hpp"
#include "../ui/ComponentRegistration.hpp"
#include "../ui/TriangleBufferEditor.hpp"
#include <OgreMeshManager.h>

// Register TriangleBuffer component
REGISTER_COMPONENT("Triangle Buffer", TriangleBufferComponent, TriangleBufferEditor)
{
    registry.registerComponent<TriangleBufferComponent>(
        "Triangle Buffer",
        std::make_unique<TriangleBufferEditor>(sceneMgr),
        // Adder
        [sceneMgr](flecs::entity e) {
            if (!e.has<TriangleBufferComponent>()) {
                e.set<TriangleBufferComponent>({});
            }
        },
        // Remover
        [sceneMgr](flecs::entity e) {
            if (e.has<TriangleBufferComponent>()) {
                auto& tb = e.get_mut<TriangleBufferComponent>();
                // Clean up Ogre entity and mesh
                if (tb.ogreEntity && sceneMgr) {
                    try {
                        sceneMgr->destroyEntity(tb.ogreEntity);
                    } catch (...) {}
                    tb.ogreEntity = nullptr;
                }
                if (!tb.meshName.empty()) {
                    try {
                        if (Ogre::MeshManager::getSingletonPtr()) {
                            Ogre::MeshManager::getSingleton().remove(tb.meshName);
                        }
                    } catch (...) {}
                }
                e.remove<TriangleBufferComponent>();
            }
        }
    );
}
