#include <epictuner/sdk/ui.hpp>
#include <optional>

using namespace et::sdk;

// The worker owns this object. Keep callback owners alive until stop completes.
class Starter : public Plugin {
    Ui ui;
    std::optional<Context> context;
    et_async_options completion{sizeof(et_async_options), ET_OPERATION_TIMEOUT_MS,
                               0, 0, this, completed};
    static void ET_CALL completed(void* owner, const et_completion* result) noexcept {
        auto& self = *static_cast<Starter*>(owner);
        try { self.context->check(*result, "Starter panel operation"); } catch (...) {}
    }
    static et_result ET_CALL input(void* owner, const et_ui_event* event) {
        auto& self = *static_cast<Starter*>(owner);
        const std::string_view node(event->node.data ? event->node.data : "", event->node.size);
        if (event->type == ET_UI_CLICK && node == "hello")
            return self.ui.patch(event->panel,
                {Ui::text("status", ET_UI_TITLE, "Hello from your compiled plugin!")},
                event->revision, event->origin, &self.completion);
        return ET_OK;
    }
public:
    static constexpr std::string_view id = "org.example.starter";
    static constexpr uint64_t capabilities = ET_CAP_UI | ET_CAP_LOG | ET_CAP_EVENTS;
    et_result start(Context& host) {
        context = host;
        auto result = host.check(ui.connect(host, input, this), "ui.connect");
        if (result != ET_OK) return result;
        PanelBuilder panel("org.example.starter.main", "Starter panel");
        panel.definition.menu = panel.keep("Examples/Starter panel");
        panel.add(ET_UI_COLUMN, "root");
        panel.add(ET_UI_TEXT, "name", "root").text(ET_UI_TITLE, "Name")
            .text(ET_UI_VALUE, "EpicTuner").boolean(ET_UI_PERSIST, true);
        panel.add(ET_UI_BUTTON, "hello", "root").text(ET_UI_TITLE, "Say hello");
        panel.add(ET_UI_LABEL, "status", "root").text(ET_UI_TITLE, "Ready");
        return host.check(ui.define(panel, &completion), "ui.define starter panel");
    }
};
ET_PLUGIN(Starter)
