#include "platformwindow.h"
#include <QGuiApplication>
#include <QtPlatformHeaders/QXcbWindowFunctions>
#include <KWayland/Client/connection_thread.h>
#include <KWayland/Client/registry.h>
#include <KWayland/Client/surface.h>
#include <kwindowsystem.h>

PlatformWindow::PlatformWindow(QWindow *parent,
                               bool panelTakefocus,
                               KWayland::Client::PlasmaShellSurface::Role surfaceRole)
    : QQuickView(parent)
    , m_isWayland(false)
    , m_panelTakefocus(panelTakefocus)
    , m_waylandSurfaceRole(surfaceRole)
{
    setColor(Qt::transparent);
    if (QGuiApplication::platformName().startsWith(QLatin1String("wayland"), Qt::CaseInsensitive)) {
        m_isWayland = true;
    }
    initWindow();
}

void PlatformWindow::initWindow()
{
    if (!m_isWayland) {
        KWindowSystem::setState(this->winId(), NET::SkipTaskbar);
        return;
    }
    using namespace KWayland::Client;
    ConnectionThread *connection = ConnectionThread::fromApplication(this);
    if (!connection) {
        return;
    }
    Registry *registry = new Registry(this);
    registry->create(connection);

    m_surface = Surface::fromWindow(this);
    if (!m_surface) {
        return;
    }
    connect(registry, &Registry::plasmaShellAnnounced, this, [this, registry](quint32 name, quint32 version) {
        m_plasmaShellInterface = registry->createPlasmaShell(name, version, this);
        m_plasmaShellSurface = m_plasmaShellInterface->createSurface(m_surface, this);
        m_plasmaShellSurface->setSkipTaskbar(true);
        m_plasmaShellSurface->setRole(m_waylandSurfaceRole);
        if (m_waylandSurfaceRole == PlasmaShellSurface::Role::Panel) {
            m_plasmaShellSurface->setPanelTakesFocus(m_panelTakefocus);
            m_plasmaShellSurface->setPanelBehavior(PlasmaShellSurface::PanelBehavior::WindowsGoBelow);
        }
    });

    registry->setup();
    connection->roundtrip();
}
