#include "AudioClip.hpp"
#include "Debug.hpp"
#include <filesystem>
#include "AudioEngine.hpp"

TSE::AudioClip::AudioClip(string path)
{
    description.path = path;
}

TSE::AudioClip::AudioClip(byte *stream, size_t size)
{
    description.audiostream = stream;
    description.dataSize = size;
}

ma_sound *TSE::AudioClip::GetAudioSound()
{
    if(description.path != ""){
        if(std::filesystem::exists(description.path))
        {
            ma_result res;
            ma_sound* sound = (ma_sound*)malloc(sizeof(*sound));

            res = ma_sound_init_from_file(AudioEngine::engine, description.path.c_str(), 0, nullptr, nullptr, sound);
            if (res != MA_SUCCESS) {
                TSE_WARNING("ma_sound_init_from_file failed: " + std::to_string(res));
                delete(sound);
                return nullptr;
            }
            return sound;
        }
        else
        {
            TSE_WARNING("Can't create ma_sound because the given path dose not exist: \n" + description.path);
        }
    }
    else if(description.audiostream != nullptr && description.dataSize > 0)
    {
        ma_result res;
        ma_decoder m_decoder;
        res = ma_decoder_init_memory(description.audiostream, description.dataSize, nullptr, &m_decoder);
        if (res != MA_SUCCESS) {
            TSE_WARNING("ma_decoder_init_memory failed: " + std::to_string(res));
            return nullptr;
        }
        ma_sound* sound = (ma_sound*)malloc(sizeof(*sound));
        res = ma_sound_init_from_data_source(AudioEngine::engine, &m_decoder, MA_SOUND_FLAG_STREAM, nullptr, sound);
        ma_decoder_uninit(&m_decoder);
        if (res != MA_SUCCESS) {
            TSE_WARNING("ma_sound_init_from_data_source failed: " + std::to_string(res));
            delete(sound);
            return nullptr;
        }
        return sound;
    }
    else
    {
        TSE_WARNING("Can't create ma_sound because description is not set, or unconfigured.");
    }
    return nullptr;
}

void TSE::AudioClip::DestroyAudioSound(ma_sound *sound)
{
    if (!sound) return;

    ma_sound_uninit(sound);
    delete sound;
}
