/**
 * AV录制器模块测试示例
 * 
 * 这个文件展示了如何使用重构后的录制器模块进行音频、视频和音视频同步录制。
 * 基于AV模块的现有组件构建，提供了统一的录制接口。
 */

#include "code/recorder/recorder.h"
#include "code/base/logger.h"
#include <QCoreApplication>
#include <QTimer>
#include <QDebug>
#include <memory>

using namespace av::recorder;
using namespace av::recorder::utils;

class RecorderTest : public QObject {
    Q_OBJECT

public:
    RecorderTest(QObject* parent = nullptr) : QObject(parent) {}
    
    void runTests() {
        // 初始化录制器模块
        auto result = RecorderModule::initialize();
        if (result != av::ErrorCode::SUCCESS) {
            qCritical() << "Failed to initialize recorder module";
            return;
        }
        
        qInfo() << "Recorder Module Version:" << QString::fromStdString(RecorderModule::getVersion());
        qInfo() << "Supported formats:" << getSupportedFormatsString();
        qInfo() << "Supported audio codecs:" << getSupportedAudioCodecsString();
        qInfo() << "Supported video codecs:" << getSupportedVideoCodecsString();
        
        // 测试音频录制
        testAudioRecording();
        
        // 延迟测试视频录制
        QTimer::singleShot(3000, this, &RecorderTest::testVideoRecording);
        
        // 延迟测试音视频同步录制
        QTimer::singleShot(6000, this, &RecorderTest::testAVRecording);
        
        // 延迟退出
        QTimer::singleShot(10000, this, &RecorderTest::cleanup);
    }
    
private slots:
    void testAudioRecording() {
        qInfo() << "\n=== Testing Audio Recording ===";
        
        // 创建音频录制器
        auto audioRecorder = createAudioRecorder();
        if (!audioRecorder) {
            qCritical() << "Failed to create audio recorder";
            return;
        }
        
        // 设置音频参数
        auto audioParams = getDefaultAudioParams();
        audioParams.outputPath = "test_audio_output.mp4";
        audioParams.sampleRate = 44100;
        audioParams.channels = 2;
        audioParams.bitrate = 128000;
        audioParams.codecName = "aac";
        
        qInfo() << "Audio params:" << formatAudioParams(audioParams);
        
        // 初始化录制器
        auto result = audioRecorder->initialize(audioParams);
        if (result != av::ErrorCode::SUCCESS) {
            qCritical() << "Failed to initialize audio recorder";
            return;
        }
        
        // 开始录制
        result = audioRecorder->startRecording();
        if (result != av::ErrorCode::SUCCESS) {
            qCritical() << "Failed to start audio recording";
            return;
        }
        
        qInfo() << "Audio recording started, will record for 2 seconds...";
        
        // 2秒后停止录制
        QTimer::singleShot(2000, [audioRecorder = std::move(audioRecorder)]() mutable {
            auto result = audioRecorder->stopRecording();
            if (result == av::ErrorCode::SUCCESS) {
                qInfo() << "Audio recording stopped successfully";
                
                // 获取统计信息
                auto stats = audioRecorder->getStatistics();
                qInfo() << "Audio recording stats:" << formatRecordingStats(stats);
            } else {
                qCritical() << "Failed to stop audio recording";
            }
        });
    }
    
    void testVideoRecording() {
        qInfo() << "\n=== Testing Video Recording ===";
        
        // 创建视频录制器
        auto videoRecorder = createVideoRecorder();
        if (!videoRecorder) {
            qCritical() << "Failed to create video recorder";
            return;
        }
        
        // 设置视频参数（使用推荐参数）
        auto videoParams = getRecommendedVideoParams();
        videoParams.outputPath = "test_video_output.mp4";
        videoParams.captureMethod = VideoCaptureMethod::SCREEN_CAPTURE;
        videoParams.monitorIndex = 0;
        videoParams.drawCursor = true;
        
        qInfo() << "Video params:" << formatVideoParams(videoParams);
        
        // 初始化录制器
        auto result = videoRecorder->initialize(videoParams);
        if (result != av::ErrorCode::SUCCESS) {
            qCritical() << "Failed to initialize video recorder";
            return;
        }
        
        // 开始录制
        result = videoRecorder->startRecording();
        if (result != av::ErrorCode::SUCCESS) {
            qCritical() << "Failed to start video recording";
            return;
        }
        
        qInfo() << "Video recording started, will record for 2 seconds...";
        
        // 2秒后停止录制
        QTimer::singleShot(2000, [videoRecorder = std::move(videoRecorder)]() mutable {
            auto result = videoRecorder->stopRecording();
            if (result == av::ErrorCode::SUCCESS) {
                qInfo() << "Video recording stopped successfully";
                
                // 获取统计信息
                auto stats = videoRecorder->getStatistics();
                qInfo() << "Video recording stats:" << formatRecordingStats(stats);
            } else {
                qCritical() << "Failed to stop video recording";
            }
        });
    }
    
    void testAVRecording() {
        qInfo() << "\n=== Testing AV Synchronized Recording ===";
        
        // 创建音视频录制器
        auto avRecorder = createAVRecorder();
        if (!avRecorder) {
            qCritical() << "Failed to create AV recorder";
            return;
        }
        
        // 设置音视频参数
        auto avParams = getDefaultAVParams();
        avParams.outputPath = "test_av_output.mp4";
        avParams.enableAudio = true;
        avParams.enableVideo = true;
        avParams.enableSync = true;
        avParams.syncThresholdMs = 40;
        avParams.dropFrameOnSync = true;
        
        // 调整音频参数
        avParams.audioParams.sampleRate = 44100;
        avParams.audioParams.channels = 2;
        avParams.audioParams.bitrate = 128000;
        
        // 调整视频参数
        avParams.videoParams.width = 1280;
        avParams.videoParams.height = 720;
        avParams.videoParams.frameRate = 30;
        avParams.videoParams.bitrate = 2000000;
        avParams.videoParams.captureMethod = VideoCaptureMethod::SCREEN_CAPTURE;
        
        qInfo() << "AV params:" << formatAVParams(avParams);
        
        // 初始化录制器
        auto result = avRecorder->initialize(avParams);
        if (result != av::ErrorCode::SUCCESS) {
            qCritical() << "Failed to initialize AV recorder";
            return;
        }
        
        // 开始录制
        result = avRecorder->startRecording();
        if (result != av::ErrorCode::SUCCESS) {
            qCritical() << "Failed to start AV recording";
            return;
        }
        
        qInfo() << "AV recording started, will record for 3 seconds...";
        
        // 3秒后停止录制
        QTimer::singleShot(3000, [avRecorder = std::move(avRecorder)]() mutable {
            auto result = avRecorder->stopRecording();
            if (result == av::ErrorCode::SUCCESS) {
                qInfo() << "AV recording stopped successfully";
                
                // 获取统计信息
                auto stats = avRecorder->getStatistics();
                qInfo() << "AV recording stats:" << formatRecordingStats(stats);
                
                // 获取同步状态
                auto syncStatus = avRecorder->getSyncStatus();
                qInfo() << "Sync status:" << formatSyncStatus(syncStatus);
            } else {
                qCritical() << "Failed to stop AV recording";
            }
        });
    }
    
    void cleanup() {
        qInfo() << "\n=== Cleaning up ===";
        
        // 清理录制器模块
        RecorderModule::cleanup();
        
        qInfo() << "Test completed, exiting...";
        QCoreApplication::quit();
    }
    
private:
    QString getSupportedFormatsString() {
        auto formats = RecorderModule::getSupportedFormats();
        QStringList list;
        for (const auto& format : formats) {
            list << QString::fromStdString(format);
        }
        return list.join(", ");
    }
    
    QString getSupportedAudioCodecsString() {
        auto codecs = RecorderModule::getSupportedAudioCodecs();
        QStringList list;
        for (const auto& codec : codecs) {
            list << QString::fromStdString(codec);
        }
        return list.join(", ");
    }
    
    QString getSupportedVideoCodecsString() {
        auto codecs = RecorderModule::getSupportedVideoCodecs();
        QStringList list;
        for (const auto& codec : codecs) {
            list << QString::fromStdString(codec);
        }
        return list.join(", ");
    }
    
    QString formatAudioParams(const AudioRecorderParams& params) {
        return QString("SR:%1Hz, CH:%2, BR:%3bps, Codec:%4")
            .arg(params.sampleRate)
            .arg(params.channels)
            .arg(params.bitrate)
            .arg(QString::fromStdString(params.codecName));
    }
    
    QString formatVideoParams(const VideoRecorderParams& params) {
        return QString("Res:%1x%2, FPS:%3, BR:%4bps, Codec:%5")
            .arg(params.width)
            .arg(params.height)
            .arg(params.frameRate)
            .arg(params.bitrate)
            .arg(QString::fromStdString(params.codecName));
    }
    
    QString formatAVParams(const AVRecorderParams& params) {
        return QString("Audio:[%1], Video:[%2], Sync:%3")
            .arg(formatAudioParams(params.audioParams))
            .arg(formatVideoParams(params.videoParams))
            .arg(params.enableSync ? "ON" : "OFF");
    }
    
    QString formatRecordingStats(const av::RecordingStatistics& stats) {
        return QString("Duration:%1s, Frames:%2, Packets:%3, Errors:%4")
            .arg(stats.durationMs / 1000.0, 0, 'f', 2)
            .arg(stats.totalFrames)
            .arg(stats.totalPackets)
            .arg(stats.errorCount);
    }
    
    QString formatSyncStatus(const av::SyncStatus& status) {
        return QString("Drift:%1ms, Dropped:%2, Duplicated:%3")
            .arg(status.avgDriftMs, 0, 'f', 2)
            .arg(status.droppedFrames)
            .arg(status.duplicatedFrames);
    }
};

int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);
    
    // 设置日志级别
    av::Logger::setLevel(av::LogLevel::INFO);
    
    qInfo() << "Starting AV Recorder Module Test...";
    qInfo() << "This test will demonstrate audio, video, and synchronized AV recording.";
    qInfo() << "Output files will be created in the current directory.";
    
    // 创建并运行测试
    RecorderTest test;
    test.runTests();
    
    return app.exec();
}

#include "test_recorder.moc"