#include "PowerFlowWidget.hpp"
#include "../Fonts.hpp"

PowerFlowWidget::PowerFlowWidget(const WidgetConfig& config)
    : Widget(config)
    , titleLabel_(nullptr)
{
}

lv_obj_t* PowerFlowWidget::create(lv_obj_t* parent) {
    obj_ = lv_obj_create(parent);
    if (obj_ == nullptr) {
        return nullptr;
    }

    lv_obj_remove_style_all(obj_);
    lv_obj_set_pos(obj_, config_.x, config_.y);
    lv_obj_set_size(obj_,
        config_.width > 0 ? config_.width : 240,
        config_.height > 0 ? config_.height : 180);
    lv_obj_clear_flag(obj_, LV_OBJ_FLAG_SCROLLABLE);

    if (config_.text[0] != '\0') {
        titleLabel_ = lv_label_create(obj_);
        lv_label_set_text(titleLabel_, config_.text);
        lv_obj_set_pos(titleLabel_, 10, 8);
        lv_obj_clear_flag(titleLabel_, LV_OBJ_FLAG_CLICKABLE);
    }

    return obj_;
}

void PowerFlowWidget::applyStyle() {
    if (obj_ == nullptr) return;

    if (config_.bgOpacity > 0) {
        lv_obj_set_style_bg_color(obj_, lv_color_make(
            config_.bgColor.r, config_.bgColor.g, config_.bgColor.b), 0);
        lv_obj_set_style_bg_opa(obj_, config_.bgOpacity, 0);
    } else {
        lv_obj_set_style_bg_opa(obj_, LV_OPA_TRANSP, 0);
    }

    if (config_.borderWidth > 0 && config_.borderOpacity > 0) {
        lv_obj_set_style_border_width(obj_, config_.borderWidth, 0);
        lv_obj_set_style_border_color(obj_, lv_color_make(
            config_.borderColor.r, config_.borderColor.g, config_.borderColor.b), 0);
        lv_obj_set_style_border_opa(obj_, config_.borderOpacity, 0);
    } else {
        lv_obj_set_style_border_width(obj_, 1, 0);
        lv_obj_set_style_border_color(obj_, lv_color_make(
            config_.textColor.r, config_.textColor.g, config_.textColor.b), 0);
        lv_obj_set_style_border_opa(obj_, LV_OPA_20, 0);
    }

    if (config_.borderRadius > 0) {
        lv_obj_set_style_radius(obj_, config_.borderRadius, 0);
    }

    applyShadowStyle();

    if (titleLabel_ != nullptr) {
        lv_obj_set_style_text_color(titleLabel_, lv_color_make(
            config_.textColor.r, config_.textColor.g, config_.textColor.b), 0);
        lv_obj_set_style_text_font(titleLabel_, Fonts::bySizeIndex(config_.fontSize), 0);
    }
}
