#include "pch.h"
#include "log.h"
#include "legacy_ui_overlay_services.h"
#include "node_popup_menu.h"
#include "node_button_custom.h"
#include "app.h"
#include <memory>

Node* NodePopupMenu::clone_instantiate() const
{
    return new NodePopupMenu();
}

void NodePopupMenu::close_popup() noexcept
{
    pp::panopainter::close_legacy_dialog_node(*this);
}

void NodePopupMenu::init()
{
    SetPosition(0, 0);
    SetWidth(100);
    SetHeight(500);
    SetPositioning(YGPositionTypeAbsolute);
    m_flood_events = true;
    m_mouse_ignore = false;
    m_capture_children = false;
}

kEventResult NodePopupMenu::handle_event(Event* e)
{
    switch (e->m_type)
    {
    case kEventType::MouseDownL:
        break;
    case kEventType::MouseUpL:
        {
            auto self = std::static_pointer_cast<NodePopupMenu>(shared_from_this());
            if (m_mouse_inside)
            {
                for (int i = 0; i < m_children.size(); i++)
                {
                    if (m_children[i]->m_mouse_inside)
                    {
                        if (on_select)
                            on_select(self.get(), i);
                        break;
                    }
                }
            }
            close_popup();
        }
        break;
    default:
        return kEventResult::Available;
        break;
    }
    return kEventResult::Consumed;
}

void NodePopupMenu::added(Node* parent)
{
    if (root() == App::I->layout.get(App::I->main_id))
        mouse_capture();
    m_mouse_ignore = false;
    m_flood_events = true;
    m_capture_children = false;
    auto self = std::static_pointer_cast<NodePopupMenu>(shared_from_this());
    for (int i = 0; i < m_children.size(); i++)
    {
        if (auto b = std::dynamic_pointer_cast<NodeButtonCustom>(m_children[i]))
        {
            std::weak_ptr<NodePopupMenu> weak_self = self;
            b->on_click = [weak_self, i](Node* target) {
                auto self = weak_self.lock();
                if (!self) {
                    return;
                }
                if (self->on_select)
                    self->on_select(self.get(), i);
            };
        }
    }
}
