/*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 "Playlist.hpp"

Playlist::Playlist() : m_playingMusic(NULL), m_volume(100)
{
    //Initialize the random number generator.
    srand( time(NULL) );
}

Playlist::~Playlist()
{
    destroy();
}

void Playlist::update()
{
    if (m_playingMusic != NULL)
        m_playingMusic->update();
}

//Switch to next song (randomly chosen) and play it
void Playlist::nextSong()
{
    if (m_playlist.size() > 0)
    {
        //Randlomly choose the next song & update
        updateMusic( m_playlist[ rand() % m_playlist.size() ] );
        
        //m_playingMusic was initialized (play it)
        m_playingMusic->play();
        
        std::cout << "Playlist : next song launched" << std::endl;
    }
}

bool Playlist::songEnded()
{
    if (m_playingMusic != NULL)
        return !(m_playingMusic->isPlaying());
    
    return true;
}

void Playlist::destroy()
{
    if (m_playingMusic != NULL)
    {
        delete m_playingMusic;
        m_playingMusic = NULL;
        
        std::cout << "Playlist : song destroyed" << std::endl;
    }
}

const SongData &Playlist::getData() const
{
    return m_playingData;
}

//Playlist handling methods
void Playlist::addSong(const SongData &songData)
{
    m_playlist.push_back(songData);
}

void Playlist::removeSong(const std::string &songPath)
{
    //Remove the song from the playlist
    std::vector<SongData>::iterator it = m_playlist.begin();
    while (it != m_playlist.end())
    {
        if (it->path == songPath)
            it = m_playlist.erase(it);
        else
            it++;
    }
}

//void Playlist::load(const std::string &playlistPath)

void Playlist::updateMusic(const SongData &data)
{
    //Destroy m_playingMusic if needed
    destroy();
    
    //Reinit it
    m_playingMusic = new Music(data.path);
    m_playingMusic->setVolume(m_volume);
    
    //Update the data
    m_playingData = data;
}

//Get and set methods
void Playlist::setVolume(float volume)
{
    if (m_volume >= 0 && m_volume <= 100)
    {
        m_volume = volume;
        
        if (m_playingMusic != NULL)
            m_playingMusic->setVolume(m_volume);
    }
        
}

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