/*Copyright (C) 2010-2020 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/>.
*/

#ifndef DEF_SOUND_ENGINE
#define DEF_SOUND_ENGINE

#include "Audio/Sound.hpp"
#include "Engines/Resources/SoundBufferManager.hpp"

#include <list>
#include <string>

//Class managing sounds.
//It can store and play simultaneously an unlimited number of sounds.
//(Also handles looping sounds)
struct LoopingSound
{
    LoopingSound(const Sound &loopingSound, float loopingPeriod, unsigned int index) :
    sound(loopingSound), period(loopingPeriod), ix(index), elapsedTime(0.f)
    {
        
    }
    
    void update(float frameTime)
    {
        float time_second = frameTime / 1000;
        
        elapsedTime += time_second;
        if (elapsedTime >= period)
        {
            sound.stop();
            elapsedTime = 0.f;
            
            sound.play();
        }
    }
    
    Sound sound;
    float period; //Looping period in seconds
    unsigned int ix; //Index in m_loopingSounds
    
    private:
        float elapsedTime;
};

class SoundEngine
{
    public:
        SoundEngine();
        
        void playSound(const std::string &soundPath);
        bool loopSound(const std::string &soundPath, float period, unsigned int &targetLoopIx);
        
        void stopLoop(unsigned int loopIx);
        void update(float frameTime);
        
        void setVolume(float volume);
        float getVolume() const;
        
        void setManager(SoundBufferManager &manager);
        const SoundBufferManager &getManager() const;
    
    private:
        bool loadSound(const std::string &soundPath, Sound &target);
        
        std::list<Sound> m_playingSounds;
        
        std::list<LoopingSound> m_loopingSounds;
        unsigned int m_loopIx; //Always a free looping sound index
        
        float m_volume;
        
        SoundBufferManager *m_manager;
};

#endif
