#include "pch.h"
#include "log.h"
#include "util.h"
#include "canvas.h"
#include "node_dialog_picker.h"

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

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

void NodeColorPicker::init()
{
    auto n = (NodeColorPicker*)init_template("color-picker");
    n->clone_copy(this);
    init_controls();
}

void NodeColorPicker::draw()
{
    NodeBorder::draw();
//    glm::vec3 rgb = glm::vec3(Canvas::I->m_current_brush.m_tip_color);
//    glm::vec3 hsv = convert_rgb2hsv(rgb);
//    m_slider_h->m_value.x = hsv.x;
//    m_slider_s->m_value.x = hsv.y;
//    m_slider_v->m_value.x = hsv.z;
//    m_slider_r->m_value.x = rgb.x;
//    m_slider_g->m_value.x = rgb.y;
//    m_slider_b->m_value.x = rgb.z;
//    m_wheel->m_hsv = hsv;
}

void NodeColorPicker::handle_value_changed()
{
    
}

void NodeColorPicker::init_controls()
{
    m_slider_h = find<NodeSliderH>("hsv-h");
    m_slider_s = find<NodeSliderH>("hsv-s");
    m_slider_v = find<NodeSliderH>("hsv-v");
    m_slider_r = find<NodeSliderH>("rgb-r");
    m_slider_g = find<NodeSliderH>("rgb-g");
    m_slider_b = find<NodeSliderH>("rgb-b");
    m_wheel = find<NodeColorWheel>("wheel");
    m_color_cur = find<NodeBorder>("color-cur");
    m_color_old = find<NodeBorder>("color-old");
    m_color_old1 = find<NodeBorder>("color-old1");
    m_color_old2 = find<NodeBorder>("color-old2");
    m_button_select = find<NodeButton>("btn-select");
    
    m_button_select->on_click = [this](Node*)
    {
        m_color_old2->m_color = m_color_old1->m_color;
        m_color_old1->m_color = m_color_old->m_color;
        m_color_old->m_color = m_color_cur->m_color;
    };
    m_wheel->on_value_changed = [this](Node*, glm::vec3 hsv)
    {
        m_slider_h->m_value.x = hsv.x;
        m_slider_s->m_value.x = hsv.y;
        m_slider_v->m_value.x = hsv.z;
        glm::vec3 rgb = convert_hsv2rgb(hsv);
        m_slider_r->m_value.x = rgb.x;
        m_slider_g->m_value.x = rgb.y;
        m_slider_b->m_value.x = rgb.z;
        m_color_cur->m_color = {rgb,1};
    };
    auto hsv_setter = [this](Node* target, float v)
    {
        m_wheel->m_hsv = get_hsv();
        glm::vec3 rgb = convert_hsv2rgb(get_hsv());
        m_color_cur->m_color = {rgb,1};
    };
    m_slider_h->on_value_changed = hsv_setter;
    m_slider_s->on_value_changed = hsv_setter;
    m_slider_v->on_value_changed = hsv_setter;
}

glm::vec3 NodeColorPicker::get_hsv() const
{
    float h = m_slider_h->get_value();
    float s = m_slider_s->get_value();
    float v = m_slider_v->get_value();
    return glm::vec3(h, s, v);
}
