#include "AudioPlayerComponent.h"
#include "../core/utils/Logging.h"
#include "../core/utils/AssetManager.h"
#include "../core/audio/AudioEngine.h"

AudioPlayerComponent::AudioPlayerComponent(Object* owner)
  : Component(owner)
{}

void AudioPlayerComponent::SetAudio(uint64_t uaid) {
    m_UAID = uaid;
}

void AudioPlayerComponent::Play() {
    if (m_UAID == 0) return;
    AudioEngine::Play(m_UAID, loop);
    AudioEngine::SetVolume(m_UAID, volume);
}

void AudioPlayerComponent::Pause() {
    if (m_UAID == 0) return;
    AudioEngine::Stop(m_UAID);
}

void AudioPlayerComponent::Stop() {
    if (m_UAID == 0) return;
    AudioEngine::Stop(m_UAID);
}

void AudioPlayerComponent::Update() 
{
    Logger::LogDepricatedWithStackTrace("AudioPlayerComponent::Update()");
    // This is never called. Its useless
    
    AudioEngine::Update();

    auto& map = AudioEngine::GetPlayingInfoMap();
    auto it  = map.find(m_UAID);
    if (it != map.end()) {
        const auto& info = it->second;
    }
}



void AudioPlayerComponent::SetLooping(bool value) {
    loop = value;
    if (m_UAID != 0) {
        AudioEngine::SetLooping(m_UAID, value);
    }
}

void AudioPlayerComponent::SetVolume(float vol) {
    volume = vol;
    if (m_UAID != 0) {
        AudioEngine::SetVolume(m_UAID, vol);
    }
}




void AudioPlayerComponent::Save(YAML::Emitter& out) const {
    out << YAML::BeginMap;
    out << YAML::Key << "type"   << YAML::Value << GetName();
    out << YAML::Key << "uaid"   << YAML::Value << m_UAID;
    out << YAML::Key << "volume" << YAML::Value << volume;
    out << YAML::Key << "loop"   << YAML::Value << loop;
    out << YAML::EndMap;
}

void AudioPlayerComponent::Load(const YAML::Node& node) {
    if (node["uaid"])   m_UAID  = node["uaid"].as<uint64_t>();
    if (node["volume"]) volume = node["volume"].as<float>();
    if (node["loop"])   loop   = node["loop"].as<bool>();
    // don’t auto-play on load
}
