#include "GL.h"

GL::GL()
{
    m_shaders.text = std::make_shared<TextShader>();
    m_shaders.text->use();
    m_shaders.text->set_texture(0);
    m_shaders.text->set_color(1.0, 1.0, 1.0, 1.0);

    m_shaders.rect = std::make_shared<RectShader>();

    GLint rect_coords[] = {
        0, 0,
        1, 0,
        1, 1,
        0, 1};
    m_rect_array = glcxx::Array::create();
    m_rect_array->bind();
    m_rect_buffer = glcxx::Buffer::create(GL_ARRAY_BUFFER, GL_STATIC_DRAW,
            rect_coords, sizeof(rect_coords));
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_INT, GL_FALSE, 0, 0);
}

void GL::draw_rect(int x, int y, int width, int height,
                   float r, float g, float b, float a)
{
    m_rect_array->bind();
    m_shaders.rect->use();
    m_shaders.rect->set_color(r, g, b, a);
    m_shaders.rect->set_position(x, y);
    m_shaders.rect->set_size(width, height);
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}

void GL::draw_character(int x, int y, uint32_t character, Font & font,
        float r, float g, float b, float a)
{
    m_shaders.text->use();
    m_shaders.text->set_color(r, g, b, a);
    m_shaders.text->set_position(x, y + font.get_baseline_offset());
    font.get_glyph(character)->render();
}

void GL::resize(int width, int height)
{
    m_shaders.text->use();
    m_shaders.text->set_viewport_size(width, height);
    m_shaders.rect->use();
    m_shaders.rect->set_viewport_size(width, height);
}
