#include "field_select_option.h"

#include "RmlUi/Core/Event.h"
#include "spdlog/spdlog.h"

namespace UI::FieldSelectOption {

void OptionClickListener::ProcessEvent(Rml::Event &) {
    SPDLOG_INFO("option clicked");

    Rml::Dictionary event_params;
    event_params["value"] = component->option_value;

    component->DispatchEvent("change", event_params);
}

void Component::on_click_option(int idx) {
    SPDLOG_INFO("on click option: {}", idx);
}

void Component::OnAttributeChange(const Rml::ElementAttributes &changed) {
    Rml::Element::OnAttributeChange(changed);

    for (auto &[key, value] : changed) {
        if (key == "value") {
            option_value = value.Get<int>();
        } else if (key == "selected") {
            if (value.Get<bool>()) {
                SetClass("selected", true);
            } else {
                SetClass("selected", false);
            }
        }
    }

    if (!built) {
        built = true;
        Build();
    }

    Update();
}

void Component::Build() {
    click_listener = new OptionClickListener(this);

    AddEventListener("click", click_listener);

    SetClass("field-select-option", true);
}

void Component::Update() {
}

} // namespace UI::FieldSelectOption
