
#include <QApplication>
#include <QFileDialog>
#include <QMessageBox>

#include <QImage>
#include <QPainter>
#include <QMimeDatabase>
#include <QMimeType>
#include <QTimer>
#include <QEventLoop>
#include <QDebug>

#include <KoDocumentEntry.h>
#include <KoPart.h>
#include <KoDocument.h>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    auto fileName = QFileDialog::getOpenFileName();
    const QString mimetype = QMimeDatabase().mimeTypeForFile(fileName).name();

    QString error;
    KoDocumentEntry documentEntry = KoDocumentEntry::queryByMimeType(mimetype);
    KoPart *part = documentEntry.createKoPart(&error);

    if (!error.isEmpty()) {
        qWarning() << "Error creating document" << mimetype << error;
        QMessageBox::warning(0, 0, "Error creating document");
        return -1;
    }

    if (!part) {
        qWarning() << "Error creating document part" << mimetype << error;
        QMessageBox::warning(0, 0, "Error creating document part");
        return -1;
    }

    KoDocument* doc = part->document();
    const QUrl url = QUrl::fromLocalFile(fileName);
    if (!doc->openUrl(url)) {
        QMessageBox::warning(0, 0, "Error opening document");
        return -1;
    }
    auto metaInfo = doc->metaObject();
    auto className = doc->metaObject()->className();
    qDebug() << metaInfo << className;

    // 等待加载
//    QEventLoop l1;
//    QTimer t1;
//    QObject::connect(&t1, &QTimer::timeout, &l1, &QEventLoop::quit);
//    t1.start(5000);
//    QObject::connect(doc, &KoDocument::completed, &l1, &QEventLoop::quit);
//    l1.exec(QEventLoop::EventLoopExec);
//    t1.stop();

    // ppt和pptx有一些元素是异步加载的，比如文字，需要再次等待
    if (fileName.endsWith("ppt") || fileName.endsWith("pptx")) {
        QEventLoop l;
        QTimer t;
        QObject::connect(&t, &QTimer::timeout, &l, &QEventLoop::quit);
        t.start(1000);
        l.exec(QEventLoop::EventLoopExec);
    }

    auto image = doc->generatePreview(QSize(512, 512));
    if (!image.isNull()) {
        image.save(fileName + ".png");
    } else {
        QMessageBox::warning(0, 0, "Error creating thumbnail");
    }

    app.quit();

    return 0;
}
