/*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 "Sound.hpp"
#include "SoundBuffer.hpp"

Sound::Sound() : m_alSource(0), m_buffer(nullptr)
{
    alGenSources(1, &m_alSource);

    setVolume(100.f);
    setPitch(1.f);
}

Sound::~Sound()
{
    alSourcei(m_alSource, AL_BUFFER, 0);
    alDeleteSources(1, &m_alSource);
}

void Sound::play()
{
    alSourcePlay(m_alSource);
}

void Sound::stop()
{
    alSourceStop(m_alSource);
}

bool Sound::isPlaying() const
{
    ALint status;
    alGetSourcei(m_alSource, AL_SOURCE_STATE, &status);
    return (status == AL_PLAYING);
}

void Sound::setBuffer(SoundBuffer &buffer)
{
    m_buffer = &buffer;
    alSourcei(m_alSource, AL_BUFFER,
              static_cast<ALint>(m_buffer->getALBuffer()));
}

void Sound::setVolume(float volume)
{
    if (volume >= 0.f && volume <= 100.f)
    {
        m_volume = volume;
        alSourcef(m_alSource, AL_GAIN, m_volume / 100.f);
    }
}

void Sound::setPitch(float pitch)
{
    if (pitch > 0.f)
    {
        m_pitch = pitch;
        alSourcef(m_alSource, AL_PITCH, m_pitch);
    }
}
