#include "pch.h"

#include <cstdint>

#include "legacy_canvas_draw_merge_services.h"
#include "log.h"
#include "legacy_ui_gl_dispatch.h"
#include "node_viewport.h"
#include "shader.h"
#include "app.h"

void NodeViewport::draw()
{
    glm::mat4 cam = glm::lookAt(glm::vec3(sinf(angle) * 10, 0, -10), glm::vec3(0, 0, 0), glm::vec3(0, -1, 0));
    glm::mat4 proj = glm::perspective<float>(glm::radians(45.f), m_clip.z / m_clip.w, .1f, 100);

    const auto vp = pp::legacy::ui_gl::query_viewport("NodeViewport");
    const auto cc = pp::legacy::ui_gl::query_clear_color("NodeViewport");

    pp::legacy::ui_gl::clear_color_buffer({ 1.f, 0.f, 0.f, 1.f }, "NodeViewport");
    auto box = m_clip * root()->m_zoom;
    glm::ivec4 c = (glm::ivec4)glm::vec4(box.x, (int)(vp[3] - box.y - box.w), box.z, box.w);
    pp::legacy::ui_gl::apply_viewport(
        static_cast<std::int32_t>(c.x + App::I->off_x),
        static_cast<std::int32_t>(c.y + App::I->off_y),
        c.z,
        c.w,
        "NodeViewport");
    TextureManager::get(m_tex_id).bind();
    m_sampler->bind(0);
    pp::legacy::ui_gl::set_blend_enabled(true, "NodeViewport");
    pp::panopainter::setup_legacy_canvas_draw_merge_texture_shader({.mvp = proj * cam, .texture_slot = 0});
    m_faces->draw_fill();
    m_sampler->unbind();
    TextureManager::get(m_tex_id).unbind();
    pp::legacy::ui_gl::set_blend_enabled(false, "NodeViewport");

    pp::legacy::ui_gl::apply_viewport(vp[0], vp[1], vp[2], vp[3], "NodeViewport");
    pp::legacy::ui_gl::set_clear_color(cc, "NodeViewport");
}
Node* NodeViewport::clone_instantiate() const
{
    return new NodeViewport;
}
void NodeViewport::create()
{
    Node::create();
    m_faces = std::make_unique<Plane>();
    m_faces->create<1>(10, 10);
    m_sampler = std::make_unique<Sampler>();
    m_sampler->create();
    TextureManager::load("data/uvs.jpg");
    m_tex_id = const_hash("data/uvs.jpg");
}
kEventResult NodeViewport::handle_event(Event* e)
{
    Node::handle_event(e);
    switch (e->m_type)
    {
    case kEventType::MouseDownL:
        dragging = true;
        drag_end = drag_start = ((MouseEvent*)e)->m_pos;
        angle_old = angle;
        break;
    case kEventType::MouseUpL:
        dragging = false;
        break;
    case kEventType::MouseMove:
        if (dragging)
        {
            drag_end = ((MouseEvent*)e)->m_pos;
            angle = angle_old + (drag_end - drag_start).x * .01f;
        }
        break;
    default:
        break;
    }
    return kEventResult::Consumed;
}
