#include "pch.h"
#include "log.h"
#include "legacy_ui_overlay_services.h"
#include "node_color_quad.h"
#include "shader.h"

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

void NodeColorQuad::clone_finalize(Node* dest) const
{
    auto n = (NodeColorQuad*)dest;
    n->m_picker = (NodeBorder*)n->m_children[0].get();
}

void NodeColorQuad::init()
{
    m_picker = new NodeBorder;
    m_picker->SetSize({ 20, 20 });
    m_picker->SetPositioning(YGPositionTypeAbsolute);
    m_picker->SetPosition(0, 0);
    m_picker->m_thinkness = 1;
    m_picker->m_color = glm::vec4(0);
    add_child(m_picker);
}

void NodeColorQuad::set_value(float x, float y)
{
    auto sz = m_size;
    auto pos = glm::clamp(glm::vec2(x, y) * sz, { 0, 0 }, sz);
    //m_picker->SetPosition(pos - m_picker->GetSize() * .5f);
    m_value = pos / glm::max({ 1,1 }, sz); // avoid div0
    if (on_value_changed)
        on_value_changed(this, m_value);
}

kEventResult NodeColorQuad::handle_event(Event* e)
{
    NodeBorder::handle_event(e);
    switch (e->m_type)
    {
    case kEventType::MouseDownL:
    {
        m_old_value = m_value;
        dragging = true;
        mouse_capture();
        auto sz = m_size;
        auto pos = glm::clamp(((MouseEvent*)e)->m_pos - m_pos, { 0, 0 }, sz);
        m_picker->SetPosition(pos - m_picker->GetSize() * .5f);
        m_value = pos / glm::max({ 1,1 }, sz); // avoid div0
        if (on_value_changed)
            on_value_changed(this, m_value);
    }
    break;
    case kEventType::MouseUpL:
        pp::panopainter::release_legacy_mouse_capture(*this);
        dragging = false;
        break;
    case kEventType::MouseMove:
        if (dragging)
        {
            auto sz = m_size;
            auto pos = glm::clamp(((MouseEvent*)e)->m_pos - m_pos, { 0, 0 }, sz);
            m_picker->SetPosition(pos - m_picker->GetSize() * .5f);
            m_value = pos / glm::max({ 1,1 }, sz); // avoid div0
            if (on_value_changed)
                on_value_changed(this, m_value);
        }
        break;
    case kEventType::MouseCancel:
        pp::panopainter::release_legacy_mouse_capture(*this);
        dragging = false;
        m_value = m_old_value;
        set_value(m_value.x, m_value.y);
        if (on_value_changed)
            on_value_changed(this, m_value);
        break;
    default:
        return kEventResult::Available;
        break;
    }
    return kEventResult::Consumed;
}

void NodeColorQuad::draw()
{
    m_picker->m_border_color = m_value.y > .5f ? glm::vec4(1) : glm::vec4(0, 0, 0, 1);
    
    auto sz = m_size;
    auto pos = glm::clamp(m_value * sz, { 0, 0 }, sz);
    m_picker->SetPosition(pos - m_picker->GetSize() * .5f);

    pp::panopainter::configure_legacy_ui_color_quad_shader(
        m_mvp,
        glm::vec4(convert_rgb2hsv(glm::vec3(m_color)), 1));
    m_plane.draw_fill();
}
