#include <AudioManager/AudioManager.hpp>
#include <Log/Log.hpp>
#include <Settings/Settings.hpp>
#include <Utilities/Utilities.hpp>

ALCdevice* AudioManager::device;
ALCcontext* AudioManager::context;
bool AudioManager::audioEnabled;

void AudioManager::init()
{
    device = alcOpenDevice(nullptr);
    if (device == nullptr)
    {
        Log::error("alcOpenDevice failed: audio will be disabled");
        return;
    }

    context = alcCreateContext(device, NULL);
    if (context == nullptr)
    {
        Log::error("alcCreateContext failed: audio will be disabled");
        return;
    }

    if (alcMakeContextCurrent(context) != ALC_TRUE)
    {
        Log::error("alcMakeContextCurrent failed: audio will be disabled");
        return;
    }

    Log::info("Audio manager initialized.");
    audioEnabled = true;
}

void AudioManager::updateListener(glm::vec3 pos, glm::vec3 vel, glm::vec3 forward, glm::vec3 up)
{
    struct
    {
        glm::vec3 at;
        glm::vec3 up;
    } orientation;

    orientation.at = forward;
    orientation.up = up;

    alListenerfv(AL_POSITION, &pos[0]);
    alListenerfv(AL_VELOCITY, &vel[0]);
    alListenerfv(AL_ORIENTATION, &orientation.at[0]);
}

void AudioManager::update()
{
    if (!audioEnabled)
    {
        return;
    }

    alListenerf(AL_GAIN, (ALfloat) settings.masterVolume / 100.0f);
}

void AudioManager::shutdown()
{
    if (context != nullptr)
    {
        alcDestroyContext(context);
    }

    if (device != nullptr)
    {
        alcCloseDevice(device);
    }
}