#include "pch.h"
#include "log.h"
#include "node_message_box.h"
#include "layout.h"

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

void NodeMessageBox::init()
{
    SetPosition(0, 0);
    SetWidthP(100);
    SetHeightP(100);
    SetPositioning(YGPositionTypeAbsolute);
    m_template = (*m_manager)[const_hash("message-box")]->m_children[0]->clone();
    add_child(m_template);
    m_title = m_template->find<NodeText>("title");
    m_message = m_template->find<NodeText>("message");
    btn_ok = m_template->find<NodeButton>("btn-ok");
    btn_ok->on_click = [&](Node*) { destroy(); };
    btn_cancel = m_template->find<NodeButton>("btn-cancel");
    on_submit = btn_cancel->on_click = [&](Node*) { destroy(); };
    m_capture_children = false; // don't capture children events on mouse_capture
}

kEventResult NodeMessageBox::handle_event(Event* e)
{
    Node::handle_event(e);
    auto ke = (KeyEvent*)e;
    switch (e->m_type)
    {
    case kEventType::KeyDown:
        break;
    case kEventType::KeyUp:
        if (ke->m_key == kKey::KeyEnter && on_submit)
            on_submit(this);
        break;
    case kEventType::KeyChar:
        break;
    default:
        return kEventResult::Available;
        break;
    }
    return kEventResult::Consumed;
}

void NodeMessageBox::added(Node* parent)
{
    Node::added(parent);
    mouse_capture();
}
