/*Copyright (C) 2010-2012 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"

Sound::Sound()
{
    alGenSources(1, &m_alSource);
}

Sound::Sound(const Sound &copied) : m_buffer(copied.m_buffer),
m_position(copied.m_position), m_velocity(copied.m_velocity), m_volume(copied.m_volume)
{
    alGenSources(1, &m_alSource);
    
    if (m_buffer != NULL)
        alSourcei(m_alSource, AL_BUFFER, m_buffer->getALBuffer());
}

Sound &Sound::operator=(const Sound &copied)
{
    if (this != &copied)
    {
        m_buffer = copied.m_buffer;
        
        m_position = copied.m_position;
        m_velocity = copied.m_velocity;
        m_volume = copied.m_volume;
        
        if (m_buffer != NULL)
            alSourcei(m_alSource, AL_BUFFER, m_buffer->getALBuffer());
        else
            alSourcei(m_alSource, AL_BUFFER, 0);
    }
    
    return (*this);
}

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

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

void Sound::pause()
{
    alSourcePause(m_alSource);
}

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

//Get and set methods
bool Sound::isPlaying() const
{
    ALint status;
    alGetSourcei(m_alSource, AL_SOURCE_STATE, &status);
    
    if (status == AL_PLAYING)
        return true;
    
    return false;
}

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

const SoundBuffer &Sound::getBuffer() const
{
    return *m_buffer;
}

void Sound::setPosition(const Vector &position)
{
    m_position = position;
    alSource3f(m_alSource, AL_POSITION, m_position.x, m_position.y, 0);
}

const Vector &Sound::getPosition() const
{
    return m_position;
}

void Sound::setVelocity(const Vector &velocity)
{
    m_velocity = velocity;
    alSource3f(m_alSource, AL_VELOCITY, m_velocity.x, m_velocity.y, 0);
}

const Vector &Sound::getVelocity() const
{
    return m_velocity;
}

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

float Sound::getVolume() const
{
    return m_volume;
}
