#include <QApplication>
#include <QMainWindow>
#include <QScreenCapture>
#include <QTimer>
#include <QDebug>
#include <QVideoSink>
#include <QVideoFrame>
#include <QImage>
#include <QMediaCaptureSession> // Added

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QMainWindow window;
    window.setWindowTitle("Screen Capture Test");
    window.resize(400, 300);
    window.show();

    QScreenCapture screenCapture;
    QVideoSink videoSink;
    QMediaCaptureSession captureSession; // Added

    captureSession.setScreenCapture(&screenCapture); // Modified
    captureSession.setVideoSink(&videoSink); // Modified

    QObject::connect(&screenCapture, &QScreenCapture::activeChanged, [&](bool active) {
        qDebug() << "Screen capture active:" << active;
    });

    QObject::connect(&screenCapture, &QScreenCapture::errorOccurred, [&](QScreenCapture::Error error) {
        qWarning() << "Screen capture error:" << error;
    });

    // Connect to videoFrameChanged to save the frame
    QObject::connect(&videoSink, &QVideoSink::videoFrameChanged, [&](const QVideoFrame &frame) {
        if (frame.isValid()) {
            qDebug() << "Frame received. Saving to captured_frame.png...";
            QImage image = frame.toImage();
            if (!image.isNull()) {
                image.save("captured_frame.png");
                qDebug() << "Frame saved. Exiting.";
                QApplication::quit(); // Quit after saving the first frame
            } else {
                qWarning() << "Failed to convert QVideoFrame to QImage.";
            }
        }
    });

    // Start screen capture after a short delay to ensure window is visible
    QTimer::singleShot(1000, [&]() {
        qDebug() << "Attempting to start screen capture...";
        screenCapture.start();
    });

    return a.exec();
}
