#include "pch.h"
#include "log.h"
#include "node_viewport.h"
#include "renderer_gl/opengl_capabilities.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);

    GLint vp[4];
    GLfloat cc[4];
    glGetIntegerv(pp::renderer::gl::viewport_query(), vp);
    glGetFloatv(pp::renderer::gl::color_clear_value_query(), cc);

    glClearColor(1, 0, 0, 1);
    glClear(pp::renderer::gl::framebuffer_color_buffer_mask());
    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);
    glViewport(c.x + App::I->off_x, c.y + App::I->off_y, c.z, c.w);
    TextureManager::get(m_tex_id).bind();
    m_sampler->bind(0);
    glEnable(pp::renderer::gl::blend_state());
    ShaderManager::use(kShader::Texture);
    ShaderManager::u_int(kShaderUniform::Tex, 0);
    ShaderManager::u_mat4(kShaderUniform::MVP, proj * cam);
    m_faces->draw_fill();
    m_sampler->unbind();
    TextureManager::get(m_tex_id).unbind();
    glDisable(pp::renderer::gl::blend_state());

    glViewport(vp[0], vp[1], vp[2], vp[3]);
    glClearColor(cc[0], cc[1], cc[2], cc[3]);
}
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;
}
