/*
 * SPDX-FileCopyrightText: 2026 ChromiumOS-Guy <chromiumos-guy-opensource@proton.me>
 * SPDX-License-Identifier: GPL-3.0-or-later
 *
 *
 * demonstrates how a portal's interactive method (setDelayedReply + Request) is
 * meant to use request.cpp. Not wired into CMakeLists.txt.
 *
 * Trimmed down from the real FileChooser::showPicker pattern (portals/FileChooser/FileChooser.cpp):
 * same setDelayedReply + Request + shared `replied` flag + reply lambda, but a QTimer stands in
 * for the QQuickView/QML picker.
 */

#include "request.h"

#include <QDBusConnection>
#include <QDBusContext>
#include <QDBusMessage>
#include <QDBusObjectPath>
#include <QObject>
#include <QTimer>
#include <QVariantMap>
#include <memory>

namespace portals {

class DummyFileChooser : public QObject, protected QDBusContext
{
    Q_OBJECT
public slots:
    // Real signature would be generated from the XML (OpenFile takes handle/app_id/parent_window/
    // title/options and returns response, results);
    uint OpenFile(const QDBusObjectPath &handle, QVariantMap &results)
    {
        Q_UNUSED(results);

        setDelayedReply(true);
        const QDBusConnection conn = connection();
        const QDBusMessage msg = message();

        auto *request = new ::Request(handle, this);

        // The picker finishing and the Request closing (peer Request.Close) race; only the first
        auto replied = std::make_shared<bool>(false);
        auto reply = [conn, msg, replied](uint response, const QVariantMap &results) {
            if (*replied)
                return;
            *replied = true;
            conn.send(msg.createReply(QVariantList { response, results }));
        };

        // Stand-in for "user picks a file in a dialog" - some real async work that finishes on
        // its own, independent of the Close() path below.
        QTimer::singleShot(3000, request, [reply, request]() {
            reply(0, QVariantMap { { "uris", QStringList { "file:///tmp/example" } } });
            request->deleteLater();
        });

        // Request::Close() just deletes the Request, so destruction is the cancellation signal.
        // It also fires on our own deleteLater() above - *replied filters that out.
        connect(request, &QObject::destroyed, this, [reply] { reply(1, QVariantMap {}); });

        return 0; // ignored: setDelayedReply(true) means QtDBus won't auto-send this.
    }
};

} // namespace portals

LOMIRI_PORTAL_PLUGIN(FileChooser)

#include "request_dummy.moc"
