﻿#include <Windows.h>
#include <string>

#include "DxLib.h"
#include "SoundManager.h"

namespace
{
    struct SoundDefinition
    {
        SoundId id;
        const wchar_t* path;
        int volume;
    };

    constexpr SoundDefinition definitions[] =
    {
        { SoundId::TitleBgm, L"Assets/Sounds/TitleBgm.wav", 140 },
        { SoundId::PlayingBgm, L"Assets/Sounds/PlayingBgm.wav", 140 },
        { SoundId::Jump, L"Assets/Sounds/Jump.wav", 200 },
        { SoundId::Land, L"Assets/Sounds/Land.wav", 180 },
        { SoundId::GameOver, L"Assets/Sounds/GameOver.wav", 220 },
        { SoundId::Goal, L"Assets/Sounds/Goal.wav", 220 }
    };
}

SoundManager::SoundManager()
{
    handles.fill(-1);
}

SoundManager::~SoundManager()
{
    Release();
}

bool SoundManager::LoadAll()
{
    Release();

    for (const SoundDefinition& definition : definitions)
    {
        const std::size_t index = static_cast<std::size_t>(definition.id);
        handles[index] = LoadSoundMem(definition.path);
        if (handles[index] == -1)
        {
            std::wstring message = definition.path;
            message += L" の読み込みに失敗しました。";
            MessageBoxW(nullptr, message.c_str(), L"Sound Load Error", MB_OK);
            Release();
            return false;
        }

        ChangeVolumeSoundMem(definition.volume, handles[index]);
    }

    return true;
}

void SoundManager::PlayBgm(SoundId id)
{
    if (currentBgm == id) return;

    StopBgm();
    PlaySoundMem(handles[static_cast<std::size_t>(id)], DX_PLAYTYPE_LOOP);
    currentBgm = id;
}

void SoundManager::PlaySe(SoundId id) const
{
    PlaySoundMem(handles[static_cast<std::size_t>(id)], DX_PLAYTYPE_BACK);
}

void SoundManager::StopBgm()
{
    if (currentBgm == SoundId::Count) return;
    StopSoundMem(handles[static_cast<std::size_t>(currentBgm)]);
    currentBgm = SoundId::Count;
}

void SoundManager::Release()
{
    StopBgm();
    for (int& handle : handles)
    {
        if (handle != -1) DeleteSoundMem(handle);
        handle = -1;
    }
}

