#include "pch.h"
#include "log.h"
#include "node_panel_color.h"
#include "legacy_ui_overlay_services.h"
#include "canvas.h"

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

void NodePanelColor::clone_finalize(Node* dest) const
{
    NodePanelColor* n = static_cast<NodePanelColor*>(dest);
    n->init_controls();
}

void NodePanelColor::init()
{
    init_template_file("data/dialogs/color-picker.xml", "tpl-panel-color");
    init_controls();
}

void NodePanelColor::init_controls()
{
    m_quad = find<NodeColorQuad>("quad");
    m_hue = find<NodeSliderHue>("hue");
    m_hue->on_hue_changed = [this](Node*, glm::vec4 hue_color) {
        m_base_color = m_quad->m_color = hue_color;
        float hue = convert_rgb2hsv(m_base_color).x;
        m_color = glm::vec4(convert_hsv2rgb(glm::vec3(hue, m_cursor.x, 1.f-m_cursor.y)), 1.f);
        m_quad->m_color = hue_color;
        if (on_color_changed)
            on_color_changed(this, m_color);
        m_interacted = true;
    };
    m_quad->on_value_changed = [this](Node*, glm::vec2 pos)
    {
        m_cursor = pos;
        float hue = convert_rgb2hsv(m_base_color).x;
        m_color = glm::vec4(convert_hsv2rgb(glm::vec3(hue, m_cursor.x, 1.f-m_cursor.y)), 1.f);
        if (on_color_changed)
            on_color_changed(this, m_color);
        m_interacted = true;
    };
    m_hue->set_value(0);
}

void NodePanelColor::set_color(glm::vec3 rgb)
{
    auto hsv = convert_rgb2hsv(rgb);
    m_hue->m_value = hsv.x;
    m_quad->m_value = glm::vec2(hsv.y, 1.f - hsv.z);
    m_quad->m_color = glm::vec4(rgb, 1);
    m_cursor = m_quad->m_value;
    m_base_color = glm::vec4(rgb, 1);
}

kEventResult NodePanelColor::handle_event(Event* e)
{
    switch (e->m_type)
    {
    case kEventType::MouseLeave:
        if (!m_interacted)
            break;
        // else fall through 
    case kEventType::MouseUpL:
        if (!m_mouse_inside)
        {
            pp::panopainter::release_legacy_mouse_capture(*this);
            if (m_parent)
            {
                pp::panopainter::detach_legacy_node_from_parent(*this);
            }
            if (on_popup_close)
            {
                on_popup_close(this);
            }
        }
        break;
    default:
        return kEventResult::Available;
        break;
    }
    return kEventResult::Available;
}

void NodePanelColor::added(Node* parent)
{
    set_color(Canvas::I->m_current_brush->m_tip_color);
    m_interacted = false;
}
