#include "include/soundengine.h"

AsyncSound::AsyncSound(QString path) {
    player = new QMediaPlayer();
    player->setMedia(QUrl(path));
    player->setVolume(50);
    player->play();
    connect(player, &QMediaPlayer::stateChanged, this, &AsyncSound::onStateChanged);
}

AsyncSound::~AsyncSound() {
    player->deleteLater();
}

QMediaPlayer* AsyncSound::operator->() const
{
    return player;
}

void AsyncSound::onStateChanged(const QMediaPlayer::State &state)
{
    if (state == QMediaPlayer::StoppedState)
        emit finished(shared_from_this());
}

QMediaPlayer& SoundEngine::player() const {
    return *player_;
}

QMediaPlaylist& SoundEngine::playlist() const {
    return *playlist_;
}

std::shared_ptr<AsyncSound> SoundEngine::playAsync(QString path) {
    auto sound_ptr = std::make_shared<AsyncSound>(path);
    if (!sound_ptr)
        return sound_ptr;

    connect(&(*sound_ptr), &AsyncSound::finished, this, &SoundEngine::onAsyncSoundFinished);
    async_sounds.insert(sound_ptr);
    return sound_ptr;
}

SoundEngine::SoundEngine(QObject *parent) : QObject(parent) {
    player_ = new QMediaPlayer();
    playlist_ = new QMediaPlaylist(player_);
    player_->setPlaylist(playlist_);
    playlist_->setPlaybackMode(QMediaPlaylist::Loop);
    player_->setVolume(50);
}

SoundEngine::~SoundEngine() {
   player_->deleteLater();
   playlist_->deleteLater();
}

void SoundEngine::onAsyncSoundFinished(const std::shared_ptr<AsyncSound> &sound)
{
    if (async_sounds.count(sound))
        async_sounds.erase(sound);
}
