#pragma once

#include <QCheckBox>
#include <QLayout>
#include <QPushButton>
#include <QTime>
#include <QTimer>
#include <QWidget>

#include <QAction>
#include <QMenu>

#include "audio_widget.h"
#include "capture_source_widget.h"
#include "qcombobox.h"
#include "qstatusbar.h"
#include "recorder/audio_recorder.h"
#include "recorder/video_recorder.h"
#include "ui/opengl_video_widget.h"
#include "ui/settings_page.h"
using namespace avrecorder::video;

class AvRecorder : public QWidget
{
    Q_OBJECT
public:
    AvRecorder(QWidget* parent = nullptr);
    ~AvRecorder();

    bool start();

    QWidget* statusBar() const { return m_statusBar; }

    void setSettings(const SettingsPage::Param& param);
public slots:
    void renderFrame();

private:
    SettingsPage::Param m_settingsParam;
    void initStatusBarUi();
    void startCapture(CaptureMethod method);
    void stopCapture();
    void startPreview();
    void dealCapture();
    void stopPreview();
    bool startStream(std::string_view path, std::string_view format);
    void stopStream();
    bool startSyncRecord(); // 开始同步录像
    void stopSyncRecord();  // 停止同步录像
    void initConnect();
    void showAudioDeviceMenu(); // 显示音频设备菜单
    void onMicrophoneDeviceSelected(); // 麦克风设备选择
    void onSpeakerDeviceSelected(); // 扬声器设备选择

private:
    AudioRecorder m_audioRecorder;
    VideoRecorder m_videoRecorder;
    AvMuxer m_avMuxer;
    AvMuxer m_recordMuxer; // 添加用于同步录像的Muxer
    // VideoRender m_videoRender;
    OpenGLVideoWidget* m_glWidget;
    AudioWidget* m_microphoneWidget = nullptr;
    AudioWidget* m_speakerWidget = nullptr;
    QPushButton* m_recordBtn = nullptr;
    QPushButton* m_liveBtn = nullptr;
    QPushButton* m_settingsBtn = nullptr;
    QPushButton* m_audioDeviceBtn = nullptr; // 音频设备选择按钮
    QCheckBox* m_isDrawCursorBox = nullptr;
    QCheckBox* m_syncRecordBox = nullptr; // 添加同步录像的复选框
    QTimer* m_videoRenderTimer = nullptr;
    QTimer m_otherTimer;
    CaptureSourceWidget* m_captureSourceWidget = nullptr;

    bool m_isRecord = false;
    bool m_isLive = false;
    bool m_isSyncRecord = false; // 是否同步录像
    QComboBox* m_captureMethodBox = nullptr;
    QLabel* m_captureStatusLabel = nullptr;
    QLabel* m_captureTimeLabel = nullptr;
    QLabel* m_fpsLabel = nullptr;
    QLabel* m_videoEncodeLabel = nullptr;
    QLabel* m_audioEncodeLabel = nullptr;
    QLabel* m_videolossRate = nullptr;

    QTime m_recordTime;
    bool m_isLocked = false;
    QStatusBar* m_statusBar = nullptr;

    void updateCaptureMethodBox(bool isMonitor);
    void onCaptureSourceChanged();
};
