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

#include "AudioLayer.h"

#include "../../engine/src/core/audio/ecs/PlaySoundComponent.h"
#include "core/audio/ecs/BlockingSoundComponent.h"
#include "ecs/standardComponents/TransformComponent.h"
#include "GLFW/glfw3.h"
#include "spdlog/spdlog.h"

void ludo::AudioLayer::onUpdate(float deltaTime) {
    Layer::onUpdate(deltaTime);

    m_audioSystem.update(deltaTime);

}

void ludo::AudioLayer::onAttachImpl() {
    Layer::onAttachImpl();

    auto rollingDiceSoundBuffer = m_assetManager.getSound("rolling_dice");
    m_diceSoundEntity = m_registry.createEntity();
    auto diceSoundSource = engine::audio::SoundSource();
    diceSoundSource.setBuffer(*rollingDiceSoundBuffer);
    m_registry.addComponent<engine::audio::SoundSource>(m_diceSoundEntity, std::move(diceSoundSource));

    m_eventBus.subscribe([this, rollingDiceSoundBuffer](const ludo::LudoEvent& event) {
            std::visit([this, rollingDiceSoundBuffer]<typename T>(const T& e) {
                if constexpr (std::is_same_v<T, ludo::DiceRolledEvent>) {
                    engine::audio::PlaySoundComponent playSound;
                    playSound.gain = 1.0f;
                    playSound.blocking = true;
                    m_registry.addComponent<engine::audio::PlaySoundComponent>(m_diceSoundEntity, playSound);
                    m_registry.addComponent<engine::audio::BlockingSoundComponent>(m_diceSoundEntity, engine::audio::BlockingSoundComponent());
                }
            }, event);
    });



    getAnimationEventBus().subscribe([this](const engine::animation::AnimationMarkerEvent& event) {
        if (event.tag == "step") {
            engine::audio::PlaySoundComponent playSound;
            auto& soundSource = this->m_registry.getComponent<engine::audio::SoundSource>(event.entity);
            playSound.gain = 1.0f;
            playSound.blocking = false;

            auto& transform = this->m_registry.getComponent<engine::TransformComponent>(event.entity);


            soundSource.setPosition(transform.m_position.x, transform.m_position.y, transform.m_position.z);
            spdlog::info("Insert PlaySoundComponent for Entity {}", event.entity.value());
            this->m_registry.addComponent<engine::audio::PlaySoundComponent>(event.entity, playSound);
        }
    });
}
