//
// Created by sasha on 04.12.2025.
//

#include "audio_manager.h"

#include "global_params.h"

AudioManager* AudioManager::instance = nullptr;


AudioManager::AudioManager() {

}

bool AudioManager::init() {
    gMixer = MIX_CreateMixerDevice( SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, nullptr );
    globalTrack = MIX_CreateTrack( gMixer );

    return true;
}

void AudioManager::playSound(const std::string &name) {
    std::string asset_path = GlobalParams::assetPath();

    if (!listAudio.contains(name)) {
        auto musicAudio = MIX_LoadAudio(gMixer, (asset_path+name).c_str(), true);
        if (!musicAudio) {
            SDL_LogError(SDL_LOG_CATEGORY_CUSTOM, "[AudioManager::playSound] Error %s",
                         SDL_GetError());
            return;
        }
        listAudio[name] = musicAudio;
    }

    MIX_SetTrackAudio( globalTrack, listAudio[name] );
    MIX_PlayTrack( globalTrack, 0 );

}

void AudioManager::stop() {
    MIX_StopAllTracks(gMixer,0);
    for (auto pair_audio : listAudio) {
        MIX_DestroyAudio( pair_audio.second );
        pair_audio.second = nullptr;
    }
    listAudio.clear();

    MIX_DestroyTrack( globalTrack );
    globalTrack = nullptr;

    //Free the mixer
    MIX_DestroyMixer( gMixer );
    gMixer = nullptr;
}
