#include "pch.h"
#include "app.h"
#include "app_core/canvas_tool_ui.h"
#include "legacy_canvas_tool_services.h"
#include "node_button.h"
#include "node_button_custom.h"

namespace {

[[nodiscard]] bool current_canvas_mode_is_draw(App& app) noexcept
{
    return app.canvas && app.canvas->m_canvas && app.canvas->m_canvas->m_current_mode == kCanvasMode::Draw;
}

template<class T>
void execute_canvas_tool_toolbar_binding(
    App& app,
    const pp::app::CanvasToolToolbarBinding& binding,
    T* button)
{
    const auto plan = pp::app::plan_canvas_tool_toolbar_binding_action(
        binding,
        current_canvas_mode_is_draw(app));
    const auto status = binding.action == pp::app::CanvasToolToolbarAction::select_mode
        ? pp::panopainter::execute_legacy_canvas_tool_plan(app, plan, button)
        : pp::panopainter::execute_legacy_canvas_tool_plan(app, plan);
    if (!status.ok())
        LOG("Canvas toolbar action failed: %s", status.message);
}

template<class T>
void bind_canvas_tool_toolbar_button(
    App& app,
    const pp::app::CanvasToolToolbarBinding& binding,
    T* button)
{
    button->on_click = [&app, binding, button](Node*) {
        execute_canvas_tool_toolbar_binding(app, binding, button);
    };
}

} // namespace

void App::init_toolbar_draw()
{
    const auto toolbar = pp::app::plan_canvas_tool_toolbar();
    bool apply_default_tool = false;
    for (const auto& binding : toolbar.bindings) {
        if (binding.custom_button) {
            if (auto* button = layout[main_id]->find<NodeButtonCustom>(binding.button_id.data())) {
                bind_canvas_tool_toolbar_button(*this, binding, button);
                apply_default_tool = apply_default_tool || binding.applies_default_on_init;
            }
        } else {
            if (auto* button = layout[main_id]->find<NodeButton>(binding.button_id.data())) {
                bind_canvas_tool_toolbar_button(*this, binding, button);
                apply_default_tool = apply_default_tool || binding.applies_default_on_init;
            }
        }
    }

    if (apply_default_tool) {
        const auto default_plan = pp::app::plan_canvas_tool_select(toolbar.default_mode);
        const auto status = pp::panopainter::execute_legacy_canvas_tool_plan(*this, default_plan);
        if (!status.ok())
            LOG("Canvas default tool action failed: %s", status.message);
    }
}
