#pragma once

#include <QImage>
#include <QMutex>
#include <QOpenGLFunctions>
#include <QOpenGLShaderProgram>
#include <QOpenGLTexture>
#include <QOpenGLWidget>
#include <QTimer>

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

class OpenGLVideoWidget : public QOpenGLWidget, protected QOpenGLFunctions
{
    Q_OBJECT
public:
    // 定义 VideoFrame 结构体
    struct VideoFrame
    {
        unsigned char* data;
        int width;
        int height;
        int format;
    };

    explicit OpenGLVideoWidget(QWidget* parent = nullptr);
    ~OpenGLVideoWidget();

    // 添加与 VideoRender 类似的接口
    bool Open(unsigned int width, unsigned int height);
    void Close();

public slots:
    bool Render(AVFrame* frame);
    
    // 原有接口
    void updateFrame(const VideoFrame& frame);
    void clearFrame();
    
    // 添加从 AVFrame 转换的方法
    bool convertFromAVFrame(AVFrame* frame);

    void setKeepAspectRatio(bool keep) { m_keepAspectRatio = keep; update(); }
    bool keepAspectRatio() const { return m_keepAspectRatio; }

    // 效果控制接口
    void setGray(bool on);
    void setThreshold(bool on, float value = 0.5f);
    void setBlur(bool on, float radius = 1.0f);
    void setReverse(bool on);
    void setColorReduce(bool on, int level = 8);
    void setGamma(bool on, float gamma = 1.0f);
    void setContrastBright(bool on, float contrast = 1.0f, float brightness = 0.0f);
    void setMirror(bool on);

    void setNoVideoTip(const QString& tip);
    void showEndTip(const QString& tip);

protected:
    void initializeGL() override;
    void paintGL() override;
    void resizeGL(int width, int height) override;

private:
    QOpenGLShaderProgram* m_program;
    GLuint m_textureId;  // 使用原生OpenGL纹理ID
    
    // 存储原始帧数据
    unsigned char* m_frameData;
    int m_frameWidth;
    int m_frameHeight;
    int m_frameFormat; // 可以用来表示像素格式
    
    QMutex m_mutex;
    bool m_frameUpdated;
    bool m_initialized;
    
    // 顶点和纹理坐标
    GLfloat m_vertices[8];
    GLfloat m_texCoords[8];

    bool m_keepAspectRatio = true;

    // 效果参数
    bool m_gray = false;
    bool m_threshold = false;
    float m_thresholdValue = 0.5f;
    bool m_blur = false;
    float m_blurRadius = 1.0f;
    bool m_reverse = false;
    bool m_colorReduce = false;
    int m_colorReduceLevel = 8;
    bool m_gamma = false;
    float m_gammaValue = 1.0f;
    bool m_contrastBright = false;
    float m_contrast = 1.0f;
    float m_brightness = 0.0f;

    bool m_mirror = false;

    QString m_noVideoTip;
    QImage m_tipImage;
    GLuint m_tipTexture;
    float m_tipAngle;
    QTimer* m_tipTimer;
    void updateTipTexture();
    void drawNoVideoTip3D();
};
