/*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 "AmbientPlayer.hpp"
#include "Audio/Music.hpp"

#include "Tools/Timer.hpp"

AmbientPlayer::AmbientPlayer(float ambientVolume) :
m_thread(nullptr), m_ambientVolume(ambientVolume), m_stop(false)
{

}

AmbientPlayer::~AmbientPlayer()
{
    stop();
}

void AmbientPlayer::play(const std::string &ambientName)
{
    stop(); //Stop the thread if any
    if (ambientName.empty())
        return;

    {
        std::lock_guard<std::mutex> lock(m_mutex);
        m_stop = false;
    }

    m_thread = new std::thread(&AmbientPlayer::threadMain, this,
                               ambientName, m_ambientVolume);
}

void AmbientPlayer::stop()
{
    if (m_thread == nullptr)
        return;

    {
        std::lock_guard<std::mutex> lock(m_mutex);
        m_stop = true;
    }

    m_thread->join();
    delete m_thread;
    m_thread = nullptr;
}

void AmbientPlayer::threadMain(std::string ambientName, float ambientVolume)
{
    Music music("audio/ambient/" + ambientName + ".ogg");
    if (!music.isOpened()) //Exit the thread is the ambient music is not opened
        return;

    music.setVolume(ambientVolume);
    music.setLooping(true);
    music.play();

    while (1)
    {
        {
            std::lock_guard<std::mutex> lock(m_mutex);
            if (m_stop)
                return;
        }

        music.update();
        Timer::sleep(Timer::duration_float_ms(10.f));
    }
}
