// IAEngine: 2D Game Engine by IA
// Copyright (C) 2025 IASoft (PVT) LTD (oss@iasoft.dev)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#include <AudioManager.hpp>
#include <IAEngine/Engine.hpp>

#include <SDL3/SDL_iostream.h>

namespace ia::iae
{
    MIX_Mixer *AudioManager::s_mixer;

    VOID AudioManager::Initialize()
    {
        if (!MIX_Init())
            THROW_UNKNOWN("Failed to initialize SDL Mixer: ", SDL_GetError());

        if (!(s_mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, NULL)))
            THROW_UNKNOWN(BuildString("Failed to create the SDL mixer: ", SDL_GetError()));
    }

    VOID AudioManager::Terminate()
    {
        MIX_DestroyMixer(s_mixer);
    }

    Handle AudioManager::CreateAudio(IN PCUINT8 encodedData, IN SIZE_T encodedDataSize)
    {
        return (Handle) MIX_LoadAudio_IO(s_mixer, SDL_IOFromConstMem(encodedData, encodedDataSize), false, true);
    }

    VOID AudioManager::DestoryAudio(IN Handle handle)
    {
        MIX_DestroyAudio((MIX_Audio*)handle);
    }
} // namespace ia::iae