#include "monitor_control.hpp"

#ifdef _MSC_VER

    #include <QtDebug>
    #include <QtGlobal>

    #include "get_last_error.hpp"
    #include "log_tr.hpp"

namespace detail {

static BOOL enumMonitorsCallback(HMONITOR hMonitor, [[maybe_unused]] HDC hDC, [[maybe_unused]] LPRECT lpRect, LPARAM lParam)
{
    std::vector<Monitor>& monitors = *reinterpret_cast<std::vector<Monitor>*>(lParam);
    DWORD numMonitors;

    if(!GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, &numMonitors)) {
        qCritical(ltr("Unable to get number of physical monitors from handle, error: %1").arg(getLastErrorString()));
        return true; // Continue enumerating
    }

    std::vector<PHYSICAL_MONITOR> physicalMonitors(numMonitors);

    if(!GetPhysicalMonitorsFromHMONITOR(hMonitor, numMonitors, physicalMonitors.data())) {
        qCritical(ltr("Unable to get physical monitors from handle, error: %1").arg(getLastErrorString()));
        return true; // Continue enumerating
    }

    for(const auto& physicalMonitor: physicalMonitors) {
        auto monitor = Monitor(hMonitor, physicalMonitor);

        if(monitor.hasBrightnessCapability()) {
            qInfo(ltr("Found brightness capable monitor '%1' with handle '0x%2' and physical handle '0x%3'")
                      .arg(monitor.m_physicalMonitor.name)
                      .arg(reinterpret_cast<qulonglong>(monitor.m_hMonitor), 0, 16)
                      .arg(reinterpret_cast<qulonglong>(monitor.m_physicalMonitor.handle), 0, 16));
            monitors.push_back(std::move(monitor));
        }
    }

    return true;
}

} // namespace detail

std::vector<Monitor> enumerateMonitors()
{
    qDebug(ltr("Enumerating monitors"));

    std::vector<Monitor> monitors;

    if(!EnumDisplayMonitors(nullptr, nullptr, detail::enumMonitorsCallback, reinterpret_cast<LPARAM>(&monitors))) {
        qCritical(ltr("Unable to enumerate display monitors, error: %1").arg(getLastErrorString()));
    }

    return monitors;
}

#endif
