#include "Gui.hpp"
#include "esp_lv_adapter.h"
#include "esp_log.h"
#include "esp_heap_caps.h"
#include "esp_system.h"
#include "Gui/WifiSetting.hpp"
#include "Gui/EthSetting.hpp"
#include "WidgetManager.hpp"
#include "lvgl.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

KnxWorker Gui::knxWorker; // Define the static member

static void screen_long_press_handler(lv_event_t * e)
{
    if (lv_event_get_code(e) == LV_EVENT_LONG_PRESSED) {
        //WifiSetting::instance().show();
        EthSetting::instance().show();
    }
}

static void widget_manager_timer_cb(lv_timer_t* timer)
{
    (void)timer;
    // Debug: Log every 100th call to verify timer is running
    /*static uint32_t callCount = 0;
    if (++callCount % 10 == 0) {
        ESP_LOGI("Gui", "Timer tick %lu", callCount);
    }*/
    WidgetManager::instance().loop();
}

void Gui::create()
{
    // Initialize WidgetManager (loads config from SD card)
    WidgetManager::instance().init();

    if (esp_lv_adapter_lock(-1) == ESP_OK) {
        // TEMP: Disabled long press handler for testing
        // lv_obj_add_event_cb(lv_scr_act(), screen_long_press_handler,
        //                     LV_EVENT_LONG_PRESSED, NULL);
        lv_timer_create(widget_manager_timer_cb, 50, nullptr);

        esp_lv_adapter_unlock();
    }

    // Apply loaded configuration (creates widgets)
    WidgetManager::instance().applyConfig();
}

void Gui::updateTemperature(float temp)
{
    // Delegate to WidgetManager for KNX group address 1
    WidgetManager::instance().onKnxValue(1, temp, TextSource::KNX_DPT_TEMP);
}
