#ifndef INCLUDESOUNDENGINE_H
#define INCLUDESOUNDENGINE_H

#include <QObject>
#include <QSound>
#include <QMediaPlayer>
#include <QMediaPlaylist>

#include <memory>
#include <set>

class AsyncSound : public QObject, public std::enable_shared_from_this<AsyncSound> {
    Q_OBJECT
public:
    AsyncSound() = delete;
    explicit AsyncSound(QString path);
    ~AsyncSound();

    QMediaPlayer* operator->() const;

private:
    QMediaPlayer* player;
private slots:
    void onStateChanged(const QMediaPlayer::State& state);
signals:
    void finished(std::shared_ptr<AsyncSound>);
};

class SoundEngine : public QObject
{
    Q_OBJECT
public:
    static SoundEngine& getInstance() {
        static SoundEngine instance(nullptr);
        return instance;
    }

    QMediaPlayer& player() const;
    QMediaPlaylist& playlist() const;
    std::shared_ptr<AsyncSound> playAsync(QString path);

private:
    SoundEngine() = delete;
    SoundEngine(const SoundEngine&) = delete;
    explicit SoundEngine(QObject *parent = nullptr);
    ~SoundEngine();

private slots:
    void onAsyncSoundFinished(const std::shared_ptr<AsyncSound> &sound);
private:
    QMediaPlayer *player_;        // Аудио плеер
    QMediaPlaylist *playlist_;    // Плейлист
    std::set<std::shared_ptr<AsyncSound>> async_sounds; // Список активных асинхронных звуков
};

#endif // INCLUDESOUNDENGINE_H
