/**
 * @file test_player_adapter.cpp
 * @brief PlayerAdapter OpenGL渲染器测试程序
 * @author AI Assistant
 * @date 2024
 */

#include "code/player/player_adapter.h"
#include "code/player/opengl_video_renderer.h"
#include <QApplication>
#include <QMainWindow>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QSlider>
#include <QLabel>
#include <QFileDialog>
#include <QMessageBox>
#include <QTimer>
#include <QComboBox>
#include <QGroupBox>
#include <iostream>

using namespace av;
using namespace av::player;

/**
 * @brief 主窗口类
 */
class PlayerAdapterTestWindow : public QMainWindow {
    Q_OBJECT

public:
    PlayerAdapterTestWindow(QWidget* parent = nullptr) : QMainWindow(parent) {
        setupUI();
        setupPlayer();
        setupConnections();
    }

private slots:
    void openFile() {
        QString filename = QFileDialog::getOpenFileName(
            this, 
            "Open Media File", 
            "", 
            "Media Files (*.mp4 *.avi *.mkv *.mov *.wmv *.flv *.webm);;All Files (*)"
        );
        
        if (!filename.isEmpty()) {
            openMediaFile(filename);
        }
    }
    
    void play() {
        if (m_playerAdapter) {
            m_playerAdapter->play();
        }
    }
    
    void pause() {
        if (m_playerAdapter) {
            m_playerAdapter->pause();
        }
    }
    
    void stop() {
        if (m_playerAdapter) {
            m_playerAdapter->stop();
        }
    }
    
    void onVolumeChanged(int value) {
        if (m_playerAdapter) {
            double volume = value / 100.0;
            m_playerAdapter->setVolume(volume);
            m_volumeLabel->setText(QString("Volume: %1%").arg(value));
        }
    }
    
    void onSpeedChanged(int value) {
        if (m_playerAdapter) {
            double speed = value / 100.0;
            m_playerAdapter->setPlaybackSpeed(speed);
            m_speedLabel->setText(QString("Speed: %1x").arg(speed, 0, 'f', 2));
        }
    }
    
    void onRendererTypeChanged(const QString& type) {
        m_rendererTypeLabel->setText(QString("Renderer: %1").arg(type));
        qDebug() << "Renderer type changed to:" << type;
    }
    
    void onOpenGLRendererInitialized() {
        qDebug() << "OpenGL renderer initialized successfully";
        m_statusLabel->setText("OpenGL renderer ready");
    }
    
    void onStateChanged(PlayerState state) {
        QString stateText;
        switch (state) {
            case PlayerState::Idle: stateText = "Idle"; break;
            case PlayerState::Opening: stateText = "Opening"; break;
            case PlayerState::Playing: stateText = "Playing"; break;
            case PlayerState::Paused: stateText = "Paused"; break;
            case PlayerState::Seeking: stateText = "Seeking"; break;
            case PlayerState::Stopped: stateText = "Stopped"; break;
            case PlayerState::Error: stateText = "Error"; break;
        }
        m_stateLabel->setText(QString("State: %1").arg(stateText));
    }
    
    void onPositionChanged(qint64 position) {
        double seconds = position / 1000000.0;
        m_positionLabel->setText(QString("Position: %1s").arg(seconds, 0, 'f', 2));
    }
    
    void onErrorOccurred(const QString& error) {
        QMessageBox::warning(this, "Error", error);
        m_statusLabel->setText("Error occurred");
    }
    
    void updateStats() {
        if (m_playerAdapter) {
            PlaybackStats stats = m_playerAdapter->getStats();
            MediaInfo info = m_playerAdapter->getMediaInfo();
            
            QString statsText = QString("Frames: %1 | Dropped: %2 | Buffer: %3")
                .arg(stats.totalFrames)
                .arg(stats.droppedFrames)
                .arg(stats.queuedVideoFrames);
            
            m_statsLabel->setText(statsText);
        }
    }

private:
    void setupUI() {
        setWindowTitle("PlayerAdapter OpenGL Test");
        setMinimumSize(900, 700);
        
        // 创建中央部件
        QWidget* centralWidget = new QWidget(this);
        setCentralWidget(centralWidget);
        
        // 创建主布局
        QVBoxLayout* mainLayout = new QVBoxLayout(centralWidget);
        
        // 创建渲染器选择区域
        QGroupBox* rendererGroup = new QGroupBox("Renderer Selection", this);
        QHBoxLayout* rendererLayout = new QHBoxLayout(rendererGroup);
        
        QPushButton* useOpenGLButton = new QPushButton("Use OpenGL Renderer", this);
        
        rendererLayout->addWidget(useOpenGLButton);
        
        mainLayout->addWidget(rendererGroup);
        
        // 创建视频显示区域
        QGroupBox* videoGroup = new QGroupBox("Video Display", this);
        QVBoxLayout* videoLayout = new QVBoxLayout(videoGroup);
        
        // 创建OpenGL渲染器
        m_openGLRenderer = new OpenGLVideoRenderer(this);
        m_openGLRenderer->setMinimumSize(640, 480);
        videoLayout->addWidget(m_openGLRenderer);
        

        
        mainLayout->addWidget(videoGroup);
        
        // 创建控制面板
        QGroupBox* controlGroup = new QGroupBox("Playback Controls", this);
        QHBoxLayout* controlLayout = new QHBoxLayout(controlGroup);
        
        // 文件操作按钮
        QPushButton* openButton = new QPushButton("Open File", this);
        QPushButton* playButton = new QPushButton("Play", this);
        QPushButton* pauseButton = new QPushButton("Pause", this);
        QPushButton* stopButton = new QPushButton("Stop", this);
        
        controlLayout->addWidget(openButton);
        controlLayout->addWidget(playButton);
        controlLayout->addWidget(pauseButton);
        controlLayout->addWidget(stopButton);
        
        // 音量控制
        QLabel* volumeLabel = new QLabel("Volume: 100%", this);
        QSlider* volumeSlider = new QSlider(Qt::Horizontal, this);
        volumeSlider->setRange(0, 100);
        volumeSlider->setValue(100);
        
        controlLayout->addWidget(volumeLabel);
        controlLayout->addWidget(volumeSlider);
        
        // 播放速度控制
        QLabel* speedLabel = new QLabel("Speed: 1.00x", this);
        QSlider* speedSlider = new QSlider(Qt::Horizontal, this);
        speedSlider->setRange(25, 200); // 0.25x - 2.0x
        speedSlider->setValue(100);
        
        controlLayout->addWidget(speedLabel);
        controlLayout->addWidget(speedSlider);
        
        mainLayout->addWidget(controlGroup);
        
        // 创建状态显示区域
        QGroupBox* statusGroup = new QGroupBox("Status Information", this);
        QGridLayout* statusLayout = new QGridLayout(statusGroup);
        
        m_stateLabel = new QLabel("State: Idle", this);
        m_positionLabel = new QLabel("Position: 0.00s", this);
        m_rendererTypeLabel = new QLabel("Renderer: None", this);
        m_statusLabel = new QLabel("Ready", this);
        m_statsLabel = new QLabel("Stats: --", this);
        
        statusLayout->addWidget(m_stateLabel, 0, 0);
        statusLayout->addWidget(m_positionLabel, 0, 1);
        statusLayout->addWidget(m_rendererTypeLabel, 1, 0);
        statusLayout->addWidget(m_statusLabel, 1, 1);
        statusLayout->addWidget(m_statsLabel, 2, 0, 1, 2);
        
        mainLayout->addWidget(statusGroup);
        
        // 保存控件引用
        m_volumeLabel = volumeLabel;
        m_speedLabel = speedLabel;
        
        // 连接信号
        connect(openButton, &QPushButton::clicked, this, &PlayerAdapterTestWindow::openFile);
        connect(playButton, &QPushButton::clicked, this, &PlayerAdapterTestWindow::play);
        connect(pauseButton, &QPushButton::clicked, this, &PlayerAdapterTestWindow::pause);
        connect(stopButton, &QPushButton::clicked, this, &PlayerAdapterTestWindow::stop);
        connect(volumeSlider, &QSlider::valueChanged, this, &PlayerAdapterTestWindow::onVolumeChanged);
        connect(speedSlider, &QSlider::valueChanged, this, &PlayerAdapterTestWindow::onSpeedChanged);
        
        // 渲染器选择按钮
        connect(useOpenGLButton, &QPushButton::clicked, this, [this]() {
            m_playerAdapter->setOpenGLVideoRenderer(m_openGLRenderer);
        });
    }
    
    void setupPlayer() {
        m_playerAdapter = std::make_unique<PlayerAdapter>(this);
        
        // 默认使用OpenGL渲染器
        m_playerAdapter->setOpenGLVideoRenderer(m_openGLRenderer);
    }
    
    void setupConnections() {
        // 连接PlayerAdapter信号
        connect(m_playerAdapter.get(), &PlayerAdapter::stateChanged, 
                this, &PlayerAdapterTestWindow::onStateChanged);
        connect(m_playerAdapter.get(), &PlayerAdapter::positionChanged, 
                this, &PlayerAdapterTestWindow::onPositionChanged);
        connect(m_playerAdapter.get(), &PlayerAdapter::errorOccurred, 
                this, &PlayerAdapterTestWindow::onErrorOccurred);
        connect(m_playerAdapter.get(), &PlayerAdapter::rendererTypeChanged, 
                this, &PlayerAdapterTestWindow::onRendererTypeChanged);
        connect(m_playerAdapter.get(), &PlayerAdapter::openGLRendererInitialized, 
                this, &PlayerAdapterTestWindow::onOpenGLRendererInitialized);
        
        // 创建定时器更新统计信息
        m_statsTimer = new QTimer(this);
        connect(m_statsTimer, &QTimer::timeout, this, &PlayerAdapterTestWindow::updateStats);
        m_statsTimer->start(500); // 每500ms更新一次
    }
    
    void openMediaFile(const QString& filename) {
        if (!m_playerAdapter) {
            return;
        }
        
        ErrorCode result = m_playerAdapter->openFile(filename);
        if (result != ErrorCode::SUCCESS) {
            QMessageBox::critical(this, "Error", 
                QString("Failed to open file: %1").arg(filename));
        } else {
            setWindowTitle(QString("PlayerAdapter OpenGL Test - %1").arg(filename));
        }
    }

private:
    std::unique_ptr<PlayerAdapter> m_playerAdapter;
    OpenGLVideoRenderer* m_openGLRenderer;
    
    QLabel* m_volumeLabel;
    QLabel* m_speedLabel;
    QLabel* m_stateLabel;
    QLabel* m_positionLabel;
    QLabel* m_rendererTypeLabel;
    QLabel* m_statusLabel;
    QLabel* m_statsLabel;
    QTimer* m_statsTimer;
};

int main(int argc, char* argv[]) {
    QApplication app(argc, argv);
    
    // 设置应用程序信息
    app.setApplicationName("PlayerAdapter OpenGL Test");
    app.setApplicationVersion("1.0");
    app.setOrganizationName("AV Player");
    
    // 创建主窗口
    PlayerAdapterTestWindow window;
    window.show();
    
    return app.exec();
}

#include "test_player_adapter.moc"