//
// Created by sebastian on 05.08.26.
//

#include "AudioSystem.h"

#include "BlockingSoundComponent.h"
#include "PlaySoundComponent.h"
#include "core/audio/SoundSource.h"

void engine::audio::AudioSystem::update(float deltaTime) const {
    std::vector<Entity> toRemove;

    for (auto& [entity, playSound] : m_registry.getPool<PlaySoundComponent>()) {
        auto& source = m_registry.getComponent<SoundSource>(entity);
        if (!playSound.started) {
            source.setGain(playSound.gain);
            source.play();
            playSound.started = true;
        } else if (!source.isPlaying()) {
            if (playSound.onFinished) {
                playSound.onFinished();
            }
            toRemove.push_back(entity);
        }
    }

    for (auto entity : toRemove) {
        m_registry.removeComponent<PlaySoundComponent>(entity);
        if (m_registry.hasComponent<BlockingSoundComponent>(entity)) {
            m_registry.removeComponent<BlockingSoundComponent>(entity);
        }
    }
}
