//
// Created by sebastian on 04.08.26.
//

#include "DebugLayer.h"

#include "ecs/standardComponents/MeshComponent.h"
#include "ecs/standardComponents/PickableComponent.h"
#include "ecs/standardComponents/TransformComponent.h"
#include "GLFW/glfw3.h"
#include "renderer/RenderQueue.h"
#include "renderer/primitives/SphereFactory.h"
#include "spdlog/spdlog.h"


void engine::DebugLayer::onUpdate(float deltaTime) {
    Layer::onUpdate(deltaTime);
    if (getKeyboard().isKeyDown(GLFW_KEY_H)) {
        m_showDebugInfo = !m_showDebugInfo;
    }
}

void engine::DebugLayer::onRender() {
    Layer::onRender();
    if (m_showDebugInfo) {
        auto pickablePool = m_entityRegistry.getPool<PickableComponent>();
        auto transforms = m_entityRegistry.getPool<engine::TransformComponent>();
        for (auto& [entity, pickableComponent] : pickablePool) {
            if (transforms.has(entity)) {
                auto meshComponent = m_entityRegistry.getComponent<engine::MeshComponent>(entity);
                glm::vec3 halfExtent = meshComponent.model.get()->getAABB().getHalfExtent();
                //spdlog::info(std::to_string(halfExtent.x) + " " + std::to_string(halfExtent.y) + " " + std::to_string(halfExtent.z));

                AABB transformedAABB = meshComponent.model->getAABB().transformed(transforms.get(entity).computeModelMatrix());
                const auto sphereTransformComp = TransformComponent(transforms.get(entity).m_position, {0,0,0}, transformedAABB.getHalfExtent());
                glm::mat4 modelMatrix = sphereTransformComp.computeModelMatrix();

                RenderCommand renderCommand(m_sphereModel, modelMatrix);
                m_renderQueue.submit(renderCommand);
            }
        }

        m_debugRenderer.render(m_renderQueue, m_camera);
    }
}

void engine::DebugLayer::onAttachImpl() {
    Layer::onAttachImpl();
}

void engine::DebugLayer::onDetachImpl() {
    Layer::onDetachImpl();
}
