/*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/>.
*/

#include "Music.hpp"

Music::Music(const std::string &relPath) : m_file(NULL), m_alSource(0),
m_format(0), m_frequency(0), m_loop(false)
{
    //Open file
    std::string path = BuildValues::data(relPath); //Locate absolute path to data.
    
    m_file = fopen(path.c_str(), "rb");
    
    if (m_file == NULL)
    {
        std::cout << "The audio music file: " << path << " could not be opened." << std::endl;
        return;
    }
    
    if (ov_open(m_file, &m_oggFile, NULL, 0) < 0)
    {
        std::cout << "The audio music file: " << path << " was not recognized as a valid vorbis file." << std::endl;
        
        ov_clear(&m_oggFile);
        m_file = NULL;
        
        return;
    }
    
    //Generate buffers & sources
    alGenBuffers(2, m_alBuffers);
    alGenSources(1, &m_alSource);
    
    setVolume(100);
    
    //Read infos
    vorbis_info *oggInfos = ov_info(&m_oggFile, -1);
    
    m_format = AL_FORMAT_MONO16;
    if (oggInfos->channels > 1) m_format = AL_FORMAT_STEREO16;
    
    m_frequency = oggInfos->rate;
    
    //Load buffers (they will swap during streaming)
    loadBuffer(m_alBuffers[0]);
    loadBuffer(m_alBuffers[1]);
    
    alSourceQueueBuffers(m_alSource, 2, m_alBuffers); //Queue them
}

Music::~Music()
{
    if (m_file != NULL) //The file failed to open, nothing to delete
    {
        //Delete buffers & source
        ALint buffersNo = 0;
        alGetSourcei(m_alSource, AL_BUFFERS_QUEUED, &buffersNo);
        
        ALuint buffer;
        for (int i = 0; i < buffersNo; i++)
            alSourceUnqueueBuffers(m_alSource, 1, &buffer);
        
        alSourcei(m_alSource, AL_BUFFER, 0);
        
        alDeleteBuffers(2, m_alBuffers);
        alDeleteSources(1, &m_alSource);
        
        //Clear file
        ov_clear(&m_oggFile);
    }
}

void Music::update()
{
    if (m_file != NULL)
    {
        ALint processed = 0; //Already played buffers
        alGetSourcei(m_alSource, AL_BUFFERS_PROCESSED, &processed);
        
        //Unqueue and update them
        for (int i = 0; i < processed; i++)
        {
            ALuint buffer;
            alSourceUnqueueBuffers(m_alSource, 1, &buffer);
            
            if (!loadBuffer(buffer)) //Loop
            {
                if (!m_loop)
                    continue;
                
                ov_time_seek(&m_oggFile, 0);
                loadBuffer(buffer);
            }
            
            alSourceQueueBuffers(m_alSource, 1, &buffer);
        }
    }
}

void Music::play()
{
    if (m_file != NULL)
        alSourcePlay(m_alSource);
}

void Music::pause()
{
    if (m_file != NULL)
        alSourcePause(m_alSource);
}

void Music::stop()
{
    if (m_file != NULL)
        alSourceStop(m_alSource);
}

bool Music::loadBuffer(ALuint buffer)
{
    if (m_file != NULL)
    {
        //Load a 44100 bits sample
        char data[44100];
        long totalSize = 44100, totalRead = 0;
        
        //Read samples (loop until completed)
        while (totalRead < totalSize)
        {
            long read = ov_read(&m_oggFile, data + totalRead, totalSize - totalRead, 0, 2, 1, NULL);
            
            if (read > 0)
                totalRead += read;
            else
                break;
        }
        
        //Attach samples to buffer
        if (totalRead > 0)
        {
            alBufferData(buffer, m_format, data, totalRead, m_frequency);
            return true;
        }
    }
    
    return false;
}

void Music::setLooping(bool loop)
{
    m_loop = loop;
}

bool Music::isLooping() const
{
    return m_loop;
}

void Music::setVolume(float volume)
{
    if (m_file != NULL && volume >= 0)
    {
        m_volume = volume;
        alSourcef(m_alSource, AL_GAIN, m_volume / 100);
    }
}

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

bool Music::isPlaying() const
{
    if (m_file != NULL)
    {
        ALint status;
        alGetSourcei(m_alSource, AL_SOURCE_STATE, &status);
        
        if (status == AL_PLAYING)
            return true;
    }
    
    return false;
}

ALenum Music::getFormat() const
{
    return m_format;
}

ALsizei Music::getFrequency() const
{
    return m_frequency;
}
