#ifndef AVPLAYER2_VIDEO_PLAY_THREAD_H
#define AVPLAYER2_VIDEO_PLAY_THREAD_H
#pragma once

#include "ThreadBase.h"
#include <QDebug>
#include <QImage>
#include <QRegularExpression>
#include "packets_sync.h"

#define PRINT_VIDEO_BUFFER_INFO 0

typedef struct Video_Resample
{
    AVFrame* pFrameRGB{nullptr};
    uint8_t* buffer_RGB{nullptr};
    struct SwsContext* sws_ctx{nullptr};
} Video_Resample;

class VideoPlayThread : public ThreadBase
{
public:
    explicit VideoPlayThread(VideoState* pState = nullptr);
    ~VideoPlayThread();

    bool init_resample_param(AVCodecContext* pVideo, bool bHardware = false);

    void setOnFrameReady(std::function<void(AVFrame*)> cb) { m_onFrameReady = std::move(cb); }
    void setOnSubtitleReady(std::function<void(const QString&)> cb) { m_onSubtitleReady = std::move(cb); }

protected:
    void run() override;

private:
    void video_refresh(VideoState* is, double* remaining_time);
    void video_image_display(VideoState* is);
    void video_display(VideoState* is);
    void final_resample_param();
    inline int compute_mod(int a, int b) { return a < 0 ? (a % b + b) : (a % b); }
    void parse_subtitle_ass(const QString& text);

private:
    VideoState* m_pState{nullptr};
    Video_Resample m_Resample;

    const static QRegularExpression m_assFilter;
    const static QRegularExpression m_assNewLineReplacer;
    std::function<void(AVFrame*)> m_onFrameReady;
    std::function<void(const QString&)> m_onSubtitleReady;
};
#endif // AVPLAYER2_VIDEO_PLAY_THREAD_H
