#include "EthSetting.hpp"
#include "../Fonts.hpp"
#include "esp_lv_adapter.h"
#include "esp_log.h"
#include <cstring>

static const char* TAG = "EthSetting";

EthSetting& EthSetting::instance() {
    static EthSetting instance;
    return instance;
}

void EthSetting::show() {
    if (visible_) {
        return;
    }

    ESP_LOGI(TAG, "Showing ETH settings");

    if (esp_lv_adapter_lock(-1) == ESP_OK) {
        createUI();
        visible_ = true;
        esp_lv_adapter_unlock();
    }
}

void EthSetting::hide() {
    if (!visible_) {
        return;
    }

    ESP_LOGI(TAG, "Hiding ETH settings");

    if (esp_lv_adapter_lock(-1) == ESP_OK) {

        if (overlay_) {
            lv_obj_del(overlay_);
            overlay_ = nullptr;
        }
        visible_ = false;
        esp_lv_adapter_unlock();
    }
}

bool EthSetting::isVisible() {
    return visible_;
}

void EthSetting::createUI() {
    overlay_ = lv_obj_create(lv_scr_act());
    lv_obj_set_size(overlay_, LV_PCT(100), LV_PCT(100));
    lv_obj_set_style_bg_color(overlay_, lv_color_hex(0x202020), 0);
    lv_obj_set_style_bg_opa(overlay_, LV_OPA_COVER, 0);
    lv_obj_set_style_text_font(overlay_, Fonts::bySizeIndex(0), 0);
    lv_obj_set_style_pad_all(overlay_, 10, 0);
    lv_obj_clear_flag(overlay_, LV_OBJ_FLAG_SCROLLABLE);

    lv_obj_t* header = lv_obj_create(overlay_);
    lv_obj_set_size(header, LV_PCT(100), 50);
    lv_obj_align(header, LV_ALIGN_TOP_MID, 0, 0);
    lv_obj_set_style_bg_color(header, lv_color_hex(0x303030), 0);
    lv_obj_set_style_pad_all(header, 5, 0);
    lv_obj_clear_flag(header, LV_OBJ_FLAG_SCROLLABLE);

    lv_obj_t* closeBtn = lv_btn_create(header);
    lv_obj_set_size(closeBtn, 40, 40);
    lv_obj_align(closeBtn, LV_ALIGN_LEFT_MID, 0, 0);
    lv_obj_set_style_bg_color(closeBtn, lv_color_hex(0x804040), 0);
    //lv_obj_add_event_cb(closeBtn, onCloseClick, LV_EVENT_CLICKED, nullptr);

    lv_obj_t* closeLbl = lv_label_create(closeBtn);
    lv_label_set_text(closeLbl, "X");
    lv_obj_center(closeLbl);

    lv_obj_t* titleLbl = lv_label_create(header);
    lv_label_set_text(titleLbl, "Eth Settings");
    lv_obj_set_style_text_font(titleLbl, Fonts::bySizeIndex(0), 0);
    lv_obj_align(titleLbl, LV_ALIGN_CENTER, 0, 0);
}


void EthSetting::onCloseClick(lv_event_t* e) {
    (void)e;
    EthSetting::instance().hide();
}
