#ifndef DOUBLEBUFFERPLAYER_H
#ifndef DOUBLEBUFFERPLAYER_H
#define DOUBLEBUFFERPLAYER_H

#include <QObject>
#include <QMediaPlayer>
#include <QUrl>
#include "logger.hpp"

class DoubleBufferPlayer : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QObject* videoOutput READ videoOutput WRITE setVideoOutput NOTIFY videoOutputChanged)

public:
    explicit DoubleBufferPlayer(QObject *parent = nullptr) : QObject(parent)
    {
        m_playerA = new QMediaPlayer(this);
        m_playerB = new QMediaPlayer(this);
        
        m_activePlayer = m_playerA;
        m_nextPlayer = m_playerB;
    }

    QObject* videoOutput() const { return m_videoOutput; }

    void setVideoOutput(QObject *output)
    {
        if (m_videoOutput != output) {
            m_videoOutput = output;
            if (m_videoOutput) {
                m_activePlayer->setVideoOutput(m_videoOutput);
            }
            emit videoOutputChanged();
        }
    }

    Q_INVOKABLE void prepareNext(const QUrl &url)
    {
        m_nextPlayer->setSource(url);
    }

    Q_INVOKABLE void swapAndPlay()
    {
        if (!m_videoOutput) return;

        m_activePlayer->stop();
        
        std::swap(m_activePlayer, m_nextPlayer);
        
        m_activePlayer->setVideoOutput(m_videoOutput);
        m_activePlayer->play();
    }

signals:
    void videoOutputChanged();

private:
    QMediaPlayer *m_playerA{nullptr};
    QMediaPlayer *m_playerB{nullptr};
    QMediaPlayer *m_activePlayer{nullptr};
    QMediaPlayer *m_nextPlayer{nullptr};
    QObject *m_videoOutput{nullptr};
};

#endif
