/*Copyright (C) 2010-2023 Duncan Deveaux

This file is part of Hikou no mizu.

Hikou no mizu is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Hikou no mizu is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Hikou no mizu.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "SoundBufferManager.hpp"

SoundBufferManager::~SoundBufferManager()
{
    std::map<std::string, SoundBuffer*>::iterator it;
    for (it = m_soundBuffersList.begin(); it != m_soundBuffersList.end(); ++it)
        delete it->second;
}

bool SoundBufferManager::getSoundBuffer(const std::string &soundPath,
                                        SoundBuffer* &target)
{
    SoundBuffer *foundSoundBuffer = findLoadedSoundBuffer(soundPath);

    if (foundSoundBuffer == nullptr) //Unknown sound buffer
        return loadSoundBuffer(soundPath, target); //Attempt to load it

    //The sound buffer was already successfully loaded: return it
    target = foundSoundBuffer;
    return true;
}

SoundBuffer *SoundBufferManager::findLoadedSoundBuffer(const std::string &soundPath)
{
    std::map<std::string, SoundBuffer*>::iterator it;
    it = m_soundBuffersList.find(soundPath);

    if (it != m_soundBuffersList.end())
        return it->second;

    return nullptr;
}

bool SoundBufferManager::loadSoundBuffer(const std::string &soundPath,
                                         SoundBuffer* &target)
{
    SoundBuffer *soundBuffer = new SoundBuffer();
    if (soundBuffer->loadFromOGG(soundPath))
    {
        //Add the loaded sound buffer to the list, it will be deleted eventually
        m_soundBuffersList[soundPath] = soundBuffer;
        target = soundBuffer;
        return true;
    }
    else
    {
        delete soundBuffer;
        return false;
    }
}
