#include "crDevAudio.h"

#include <imgui.h>

#include "crApp.h"
#include "crAudio.h"

void crDevAudio::Init( crApp* app )
{
    _app = app;
}
void crDevAudio::Cleanup()
{
    _app = nullptr;
}

void crDevAudio::TryRenderPanel()
{
    if( enabled == false )
        return;

    crAudio* audio = _app->audio;

    ImGui::PushStyleVar( ImGuiStyleVar_FramePadding, ImVec2( 4.0f, 0.0f ) );
    ImGui::PushStyleVar( ImGuiStyleVar_ItemSpacing, ImVec2( 8.0f, 2.0f ) );

    ImGui::SetNextWindowPos( ImVec2( 10.0f, 30.0f ), ImGuiCond_FirstUseEver );
    ImGui::SetNextWindowSize( ImVec2( 240.0f, 0.0f ), ImGuiCond_FirstUseEver );
    ImGui::SetNextWindowCollapsed( true, ImGuiCond_FirstUseEver );

    if( ImGui::Begin( "Audio", nullptr, ImGuiWindowFlags_NoSavedSettings ) )
    {
        {// volumes
            float master = audio->GetMasterVolume();
            if( ImGui::SliderFloat( "Master", &master, 0.0f, 1.0f ) )
                audio->SetMasterVolume( master );

            float bgm = audio->GetBgmVolume();
            if( ImGui::SliderFloat( "BGM##vol", &bgm, 0.0f, 1.0f ) )
                audio->SetBgmVolume( bgm );

            float sfx = audio->GetSfxVolume();
            if( ImGui::SliderFloat( "SFX##vol", &sfx, 0.0f, 1.0f ) )
                audio->SetSfxVolume( sfx );
        }

        ImGui::Separator();

        {// bgm — streamed, no registry to enumerate
            ImGui::InputText( "BGM", _bgmName, sizeof( _bgmName ) );

            if( ImGui::Button( "Play##bgm" ) )
                audio->PlayBgm( _bgmName, _bgmLoop );
            ImGui::SameLine();
            if( ImGui::Button( "Stop##bgm" ) )
                audio->StopBgm();
            ImGui::SameLine();
            ImGui::Checkbox( "Loop", &_bgmLoop );
        }

        ImGui::Separator();

        {// sfx
            const int32_t sfxCount = audio->SfxCount();
            if( _sfxIndex >= sfxCount )
                _sfxIndex = ( sfxCount - 1 );   // -1 while nothing is loaded

            const char* preview = ( _sfxIndex >= 0 ) ? audio->SfxName( _sfxIndex ) : "<none loaded>";
            if( ImGui::BeginCombo( "SFX", preview ) )
            {
                for( int32_t i = 0; i < sfxCount; ++i )
                {
                    if( ImGui::Selectable( audio->SfxName( i ), ( i == _sfxIndex ) ) )
                        _sfxIndex = i;
                }
                ImGui::EndCombo();
            }

            ImGui::SliderFloat( "Volume##sfx", &_sfxVolume, 0.0f, 1.0f );
            ImGui::SliderFloat( "Pan##sfx", &_sfxPan, -1.0f, 1.0f );

            if( ImGui::Button( "Play##sfx" ) )
            {
                if( _sfxIndex >= 0 )
                    audio->PlaySfx( _sfxIndex, _sfxVolume, _sfxPan );
            }
        }
    }
    ImGui::End();

    ImGui::PopStyleVar( 2 );
}
