#ifndef AV_RECORDER_VIDEO_WIDGET_H
#define AV_RECORDER_VIDEO_WIDGET_H

#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <QOpenGLExtraFunctions>
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>
#include <QMutex>
#include <QTimer>
#include <QImage>
#include <QPainter>
#include <QResizeEvent>
#include <QMouseEvent>
#include <memory>

extern "C" {
#include <libavutil/frame.h>
#include <libavutil/imgutils.h>
}

/**
 * 录制器视频预览组件
 * 
 * 基于OpenGL的高性能视频显示组件，支持：
 * - YUV和RGB格式显示
 * - 硬件加速渲染
 * - 保持宽高比
 * - 实时帧率显示
 * - 多种视觉效果
 */
class RecorderVideoWidget : public QOpenGLWidget, protected QOpenGLExtraFunctions {
    Q_OBJECT

public:
    /**
     * 视频帧结构
     */
    struct VideoFrame {
        uint8_t* data[4] = {nullptr};
        int linesize[4] = {0};
        int width = 0;
        int height = 0;
        int format = 0; // AVPixelFormat
        int64_t pts = 0;
        
        VideoFrame() = default;
        ~VideoFrame() {
            for (int i = 0; i < 4; ++i) {
                if (data[i]) {
                    av_free(data[i]);
                    data[i] = nullptr;
                }
            }
        }
        
        // 禁用拷贝，只允许移动
        VideoFrame(const VideoFrame&) = delete;
        VideoFrame& operator=(const VideoFrame&) = delete;
        VideoFrame(VideoFrame&& other) noexcept {
            *this = std::move(other);
        }
        VideoFrame& operator=(VideoFrame&& other) noexcept {
            if (this != &other) {
                for (int i = 0; i < 4; ++i) {
                    data[i] = other.data[i];
                    linesize[i] = other.linesize[i];
                    other.data[i] = nullptr;
                    other.linesize[i] = 0;
                }
                width = other.width;
                height = other.height;
                format = other.format;
                pts = other.pts;
            }
            return *this;
        }
    };

public:
    explicit RecorderVideoWidget(QWidget* parent = nullptr);
    ~RecorderVideoWidget();

    /**
     * 初始化视频显示
     */
    bool initialize(int width, int height, int format);
    
    /**
     * 清理资源
     */
    void cleanup();
    
    /**
     * 更新视频帧
     */
    bool updateFrame(AVFrame* frame);
    
    /**
     * 更新视频帧（自定义格式）
     */
    bool updateFrame(const VideoFrame& frame);
    
    /**
     * 清空当前帧
     */
    void clearFrame();
    
    /**
     * 设置保持宽高比
     */
    void setKeepAspectRatio(bool keep) {
        m_keepAspectRatio = keep;
        update();
    }
    
    /**
     * 获取是否保持宽高比
     */
    bool keepAspectRatio() const { return m_keepAspectRatio; }
    
    /**
     * 设置显示FPS
     */
    void setShowFPS(bool show) {
        m_showFPS = show;
        update();
    }
    
    /**
     * 获取当前FPS
     */
    double getCurrentFPS() const { return m_currentFPS; }
    
    /**
     * 设置无视频提示文本
     */
    void setNoVideoText(const QString& text) {
        m_noVideoText = text;
        update();
    }
    
    /**
     * 设置背景颜色
     */
    void setBackgroundColor(const QColor& color) {
        m_backgroundColor = color;
        update();
    }
    
    // 视觉效果
    void setGrayscale(bool enable);
    void setFlipHorizontal(bool enable);
    void setFlipVertical(bool enable);
    void setBrightness(float brightness); // -1.0 to 1.0
    void setContrast(float contrast);     // 0.0 to 2.0
    void setSaturation(float saturation); // 0.0 to 2.0

protected:
    void initializeGL() override;
    void paintGL() override;
    void resizeGL(int width, int height) override;
    void mousePressEvent(QMouseEvent* event) override;
    void mouseDoubleClickEvent(QMouseEvent* event) override;

private slots:
    void updateFPS();

signals:
    /**
     * 鼠标点击信号
     */
    void clicked(QPoint position);
    
    /**
     * 双击信号
     */
    void doubleClicked(QPoint position);

private:
    /**
     * 初始化着色器
     */
    bool initShaders();
    
    /**
     * 创建纹理
     */
    void createTextures();
    
    /**
     * 更新纹理数据
     */
    void updateTextures();
    
    /**
     * 计算显示矩形
     */
    QRectF calculateDisplayRect() const;
    
    /**
     * 绘制无视频提示
     */
    void drawNoVideoHint();
    
    /**
     * 绘制FPS信息
     */
    void drawFPSInfo();
    
    /**
     * 从AVFrame复制数据
     */
    bool copyFromAVFrame(AVFrame* frame);
    
    /**
     * 从VideoFrame复制数据
     */
    bool copyFromVideoFrame(const VideoFrame& frame);
    
    /**
     * 分配帧缓冲区
     */
    bool allocateFrameBuffer(int width, int height, int format);
    
    /**
     * 释放帧缓冲区
     */
    void freeFrameBuffer();

private:
    // OpenGL资源
    std::unique_ptr<QOpenGLShaderProgram> m_shaderProgram;
    GLuint m_textureY;
    GLuint m_textureU;
    GLuint m_textureV;
    GLuint m_textureRGB;
    GLuint m_VAO;
    GLuint m_VBO;
    
    // 帧数据
    uint8_t* m_frameData[4];
    int m_frameLinesize[4];
    int m_frameWidth;
    int m_frameHeight;
    int m_frameFormat;
    bool m_frameReady;
    
    // 显示设置
    bool m_keepAspectRatio;
    bool m_showFPS;
    QString m_noVideoText;
    QColor m_backgroundColor;
    
    // 视觉效果
    bool m_grayscale;
    bool m_flipHorizontal;
    bool m_flipVertical;
    float m_brightness;
    float m_contrast;
    float m_saturation;
    
    // FPS计算
    QTimer* m_fpsTimer;
    int m_frameCount;
    double m_currentFPS;
    qint64 m_lastFPSUpdate;
    
    // 线程安全
    mutable QMutex m_mutex;
    
    // 初始化状态
    bool m_initialized;
    
    // 顶点数据
    static constexpr float VERTICES[] = {
        // 位置        // 纹理坐标
        -1.0f, -1.0f,  0.0f, 1.0f,
         1.0f, -1.0f,  1.0f, 1.0f,
         1.0f,  1.0f,  1.0f, 0.0f,
        -1.0f,  1.0f,  0.0f, 0.0f
    };
    
    static constexpr unsigned int INDICES[] = {
        0, 1, 2,
        2, 3, 0
    };
};

#endif // AV_RECORDER_VIDEO_WIDGET_H