#include "qwaylandukuioutputv1_p.h"

#include "qwaylanddisplay_p.h"
#include "qwaylandscreen_p.h"

#include <QtGui/qpa/qwindowsysteminterface.h>

namespace QtWaylandClient {

QWaylandUkuiOutputV1::QWaylandUkuiOutputV1(struct ::ukui_output_v1 *output)
    : QtWayland::ukui_output_v1(output)
{
}

void QWaylandUkuiOutputV1::ukui_output_v1_name(const QString &name)
{
    m_outputName = name;
}

void QWaylandUkuiOutputV1::ukui_output_v1_usable_area(int32_t x, int32_t y, int32_t width, int32_t height)
{
    m_availableGeometry = QRect(x, y, width, height);
}

void QWaylandUkuiOutputV1::setFinishedHandler(const std::function<void()> &handler)
{
    m_finishedHandler = handler;
}

void QWaylandUkuiOutputV1::ukui_output_v1_finished()
{
    if (m_finishedHandler) {
        m_finishedHandler();
    }
    m_finishedHandler = nullptr; // Clear the handler to avoid multiple calls
}

QWaylandUkuiOutputManagementV1::QWaylandUkuiOutputManagementV1(QWaylandDisplay *display, uint id, uint version)
    : QtWayland::ukui_output_management_v1(display->wl_registry(), id, qMin(version, uint(1)))
    , m_display(display)
{
}

QList<QWaylandUkuiOutputV1 *> QWaylandUkuiOutputManagementV1::ukuiOutputs() const
{
    return m_ukuiOutputs;
}

QWaylandUkuiOutputV1 *QWaylandUkuiOutputManagementV1::findUKuiOutput(const QString &name) const
{
    auto it = std::find_if(m_ukuiOutputs.begin(), m_ukuiOutputs.end(), [&name](QWaylandUkuiOutputV1 *ukuiOutput) {
        return ukuiOutput->name() == name;
    });
    return (it != m_ukuiOutputs.end()) ? *it : nullptr;
}

void QWaylandUkuiOutputManagementV1::ukui_output_management_v1_output(struct ::ukui_output_v1 *output)
{
    auto *ukuiOutput = new QWaylandUkuiOutputV1(output);
    m_ukuiOutputs.append(ukuiOutput);

    ukuiOutput->setFinishedHandler([this, ukuiOutput]() {
        m_ukuiOutputs.removeAll(ukuiOutput);
        delete ukuiOutput;
    });
}

void QWaylandUkuiOutputManagementV1::ukui_output_management_v1_done()
{
    const auto screens = m_display->screens();
    for (auto *screen : screens) {
        const auto* ukuiOutput = findUKuiOutput(screen->name());
        if (ukuiOutput) {
            QWindowSystemInterface::handleScreenGeometryChange(screen->screen(), screen->geometry(), ukuiOutput->availableGeometry());
        }
    }
}

} // namespace QtWaylandClient
