#include "desktop_integration.h"

#include <QDesktopServices>
#include <QProcess>
#include <QUrl>

QList<DetachedCommand> browserOpenCommands(const QString &url)
{
    QList<DetachedCommand> commands;
#ifdef Q_OS_LINUX
    commands.push_back({QStringLiteral("xdg-open"), QStringList{url}});
    commands.push_back({QStringLiteral("gio"), QStringList{QStringLiteral("open"), url}});
#else
    Q_UNUSED(url);
#endif
    return commands;
}

QString normalizedQtPlatformPlugin(const QString &platform,
                                   const QString &desktopSession,
                                   bool hasWaylandDisplay)
{
#ifdef Q_OS_LINUX
    const QString normalizedDesktop = desktopSession.trimmed().toLower();
    const QString normalizedPlatform = platform.trimmed();
    if (!hasWaylandDisplay &&
        (normalizedDesktop.contains(QStringLiteral("dde")) ||
         normalizedDesktop.contains(QStringLiteral("deepin"))) &&
        normalizedPlatform.startsWith(QStringLiteral("dxcb"))) {
        return QStringLiteral("xcb");
    }
#else
    Q_UNUSED(platform);
    Q_UNUSED(desktopSession);
    Q_UNUSED(hasWaylandDisplay);
#endif
    return platform;
}

bool openUrlWithDesktopIntegration(const QString &url, QString *error)
{
    const QUrl qurl = QUrl::fromUserInput(url.trimmed());
    if (!qurl.isValid() || qurl.isEmpty()) {
        if (error) {
            *error = QStringLiteral("无效链接：%1").arg(url);
        }
        return false;
    }

    for (const DetachedCommand &command : browserOpenCommands(qurl.toString())) {
        if (QProcess::startDetached(command.program, command.arguments)) {
            if (error) {
                error->clear();
            }
            return true;
        }
    }

    if (QDesktopServices::openUrl(qurl)) {
        if (error) {
            error->clear();
        }
        return true;
    }

    if (error) {
        *error = QStringLiteral("无法使用 xdg-open 打开链接：%1").arg(qurl.toString());
    }
    return false;
}
