#include "pch.h"
#include "log.h"
#include "legacy_ui_overlay_services.h"
#include "node_button_custom.h"

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

void NodeButtonCustom::clone_copy(Node* dest) const
{
    NodeBorder::clone_copy(dest);
    NodeButtonCustom* n = static_cast<NodeButtonCustom*>(dest);
    n->color_normal = color_normal;
    n->color_hover = color_hover;
    n->color_down = color_down;
    n->color_active = color_active;
    n->m_active = m_active;
    n->m_mouse_ignore = false;
    n->m_color = color_normal;
}

void NodeButtonCustom::loaded()
{
    NodeBorder::loaded();
    //m_thinkness = 1;
    //m_border_color = glm::vec4(0, 0, 0, 1);
    m_color = color_normal;
    m_mouse_ignore = false;
}

bool NodeButtonCustom::is_active()
{
    return m_active;
}

void NodeButtonCustom::set_active(bool active)
{
    if (m_active == active)
        return;
    m_active = active;
    m_color = m_active ? color_active : (m_mouse_inside ? color_hover : color_normal);
}

void NodeButtonCustom::set_color(const glm::vec4& c)
{
    color_normal = c;
    m_color = m_active ? color_active : (m_mouse_inside ? color_hover : color_normal);
}

kEventResult NodeButtonCustom::handle_event(Event* e)
{
    NodeBorder::handle_event(e);
    switch (e->m_type)
    {
    case kEventType::MouseEnter:
        m_color = m_active ? color_active : color_hover;
        break;
    case kEventType::MouseLeave:
        m_color = m_active ? color_active : color_normal;
        break;
    case kEventType::MouseDownL:
        m_color = m_active ? color_active : color_down;
        mouse_capture();
        break;
    case kEventType::MouseUpL:
        // if using touch or stylus, unfocus the button
        if (((MouseEvent*)e)->m_source == kEventSource::Mouse)
            m_color = m_active ? color_active : (m_mouse_inside ? color_hover : color_normal);
        else
            m_color = m_active ? color_active : color_normal;
        pp::panopainter::release_legacy_mouse_capture(*this);
        if (m_mouse_inside && on_click != nullptr)
            on_click(this);
        break;
    case kEventType::MouseCancel:
        m_color = m_active ? color_active : color_normal;
        pp::panopainter::release_legacy_mouse_capture(*this);
        break;
    default:
        return kEventResult::Available;
        break;
    }
    return kEventResult::Consumed;
}

void NodeButtonCustom::parse_attributes(kAttribute ka, const tinyxml2::XMLAttribute* attr)
{
    NodeBorder::parse_attributes(ka, attr);
    switch (ka)
    {
    case kAttribute::Color:
        color_normal = m_color;
        break;
    default:
        break;
    }
}
