// SPDX-FileCopyrightText: 2024 KylinSoft Co., Ltd.
//
// SPDX-License-Identifier: GPL-1.0-or-later

#include "ukuishellintegration.h"
#include "logging.h"
#include "ukuishellsurface.h"
#include "ukuishellsurfacev1.h"
#include "xdgdecorationv1.h"

#include <QtWaylandClient/private/qwaylanddisplay_p.h>
#include <QtWaylandClient/private/qwaylandwindow_p.h>

namespace QtWaylandClient
{

bool UkuiShellIntegration::initialize(QWaylandDisplay *display)
{
    for (auto global : display->globals()) {
        if (global.interface == QLatin1String("xdg_wm_base")) {
            m_ukuiShell.reset(new UkuiShell(display, global.id, global.version));
            break;
        }
    }

    if (!m_ukuiShell) {
        qCDebug(UKUI_SHELL) << "Couldn't find global xdg_wm_base for xdg-shell stable";
        return false;
    }

    return QWaylandShellIntegration::initialize(display);
}

QWaylandShellSurface *UkuiShellIntegration::createShellSurface(QWaylandWindow *window)
{
    auto *shellSurface = m_ukuiShell->getUkuiShellSurface(window);
    if (shellSurface) {
        m_shellSurfaces[window->window()] = shellSurface;
    }
    return shellSurface;
}

void *UkuiShellIntegration::nativeResourceForWindow(const QByteArray &resourceString, QWindow *window)
{
    QByteArray lowerCaseResource = resourceString.toLower();
    if (lowerCaseResource == QByteArrayLiteral("ukui_shell")) {
        if (m_ukuiShell) {
            if (m_ukuiShell->QtwaylandUkuiShellV1())
                return m_ukuiShell->QtwaylandUkuiShellV1()->object();
            if (m_ukuiShell->QtwaylandUkuiShell())
                return m_ukuiShell->QtwaylandUkuiShell()->object();
        }
        return nullptr;
    } else if (lowerCaseResource == QByteArrayLiteral("ukui_surface_v1")) {
        auto surface = m_shellSurfaces.at(window);
        if (auto ukuiSurfaceV1 = static_cast<UkuiShellSurfaceV1 *>(surface)) {
            return ukuiSurfaceV1->ukui_surface_v1::object();
        }
        return nullptr;
    }

    return nullptr;
}
}
