#include "ProceduralMaterial.hpp"
#include "../ui/ComponentRegistration.hpp"
#include "../ui/ProceduralMaterialEditor.hpp"
#include <OgreMaterialManager.h>
#include <OgreRTShaderSystem.h>

// Register ProceduralMaterial component
REGISTER_COMPONENT_GROUP("Procedural Material", "Material", ProceduralMaterialComponent, ProceduralMaterialEditor)
{
    registry.registerComponent<ProceduralMaterialComponent>(
        "Procedural Material", "Material",
        std::make_unique<ProceduralMaterialEditor>(sceneMgr),
        // Adder
        [sceneMgr](flecs::entity e) {
            if (!e.has<ProceduralMaterialComponent>()) {
                e.set<ProceduralMaterialComponent>({});
            }
        },
        // Remover
        [sceneMgr](flecs::entity e) {
            if (e.has<ProceduralMaterialComponent>()) {
                auto& material = e.get_mut<ProceduralMaterialComponent>();
                // Clean up Ogre material - wrap in try/catch since MaterialManager may be shutting down
                if (material.ogreMaterial) {
                    try {
                        Ogre::RTShader::ShaderGenerator *shaderGen =
                            Ogre::RTShader::ShaderGenerator::getSingletonPtr();
                        if (shaderGen) {
                            shaderGen->removeAllShaderBasedTechniques(
                                *material.ogreMaterial);
                        }
                        if (Ogre::MaterialManager::getSingletonPtr()) {
                            Ogre::MaterialManager::getSingleton().remove(material.ogreMaterial);
                        }
                    } catch (...) {}
                    material.ogreMaterial.reset();
                }
                e.remove<ProceduralMaterialComponent>();
            }
        }
    );
}
