//
// Created by sebastian on 04.08.26.
//

#include "SoundUploader.h"

#include <dr_wav.h>

#include "core/audio/AudioDevice.h"

engine::audio::SoundBuffer engine::SoundUploader::upload(const RawSoundData &data) {
    auto* context = alcGetCurrentContext();

    if (!context) {
        std::cerr << "NO OPENAL CONTEXT IN UPLOAD THREAD\n";
    }

    ALenum format;
    if (data.channels == 1) {
        format = AL_FORMAT_MONO16;
    } else if (data.channels == 2) {
        format = AL_FORMAT_STEREO16;
    } else {
        throw std::runtime_error("Unsupported channel count");
    }

    ALuint bufferID = 0;
    alGenBuffers(1, &bufferID);

    alBufferData(
        bufferID,
        format,
        data.pcmData.data(),
        static_cast<ALsizei>(data.pcmData.size()),
        data.sampleRate
    );

    audio::checkAlError("alBufferData");

    return audio::SoundBuffer(bufferID);
}
