#include "pch.h"
#include "log.h"
#include "legacy_ui_overlay_services.h"
#include "node_input_box.h"
#include "layout.h"

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

void NodeInputBox::init()
{
    SetPosition(0, 0);
    SetWidthP(100);
    SetHeightP(100);
    SetPositioning(YGPositionTypeAbsolute);
    add_child_file("data/dialogs/input-box.xml", "input-box");
    m_title = find<NodeText>("title");
    m_field_name = find<NodeText>("field-name");
    m_field_text = find<NodeTextInput>("field-text");
    btn_ok = find<NodeButton>("btn-ok");
    btn_ok->on_click = [&](Node*) { 
        if (on_submit)
            on_submit(this, m_field_text->m_text);
    };
    btn_cancel = find<NodeButton>("btn-cancel");
    pp::panopainter::bind_legacy_click_destroys_node(*btn_cancel, *this);
    m_capture_children = false; // don't capture children events on mouse_capture
}

kEventResult NodeInputBox::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, m_field_text->m_text);
        break;
    case kEventType::KeyChar:
        break;
    default:
        return kEventResult::Available;
        break;
    }
    return kEventResult::Consumed;
}

void NodeInputBox::added(Node* parent)
{
    Node::added(parent);
    if (added_to_root())
    {
        mouse_capture();
        m_field_text->key_capture();
    }
}
