/**
 * paradiso - Paradigmen der Softwareentwicklung
 *
 * (c) Copyright 2023 Hartmut Seichter
 *
 */

#include <paradiso/bitmap.hpp>
#include <paradiso/context.hpp>
#include <paradiso/geometry.hpp>
#include <paradiso/renderer.hpp>
#include <paradiso/shader.hpp>
#include <paradiso/sprite.hpp>
#include <paradiso/window.hpp>

#include <iomanip>
#include <iostream>

void setup_shaders(paradiso::Shader& shader) {
    const auto unlit_v = R"(
#version 330 core

layout (location = 0) in vec3 vertices;
layout (location = 1) in vec3 normals;
layout (location = 2) in vec2 texture_coords;

// uniform mat4 model;
// uniform mat4 view;
// uniform mat4 projection;

out vec2 tex_c;

void main() {
    tex_c = texture_coords;
    // gl_Position = projection * view * model * vec4(vertices, 1.0);
     gl_Position = vec4(vertices, 1.0);
}
)";

    const auto unlit_f = R"(
#version 330 core

uniform vec4 color = vec4(1.0, 0.0, 0.0, 1.0);
uniform sampler2D tex_color;

in vec2 tex_c;

out vec4 frag_color;

void main() {
    frag_color = texture(tex_color,tex_c); // *  color;
})";

    shader.set_source(paradiso::Shader::Type::Vertex, unlit_v);
    shader.set_source(paradiso::Shader::Type::Fragment, unlit_f);

    shader.build();
}

auto main() -> int {

    auto checker_board = paradiso::Bitmap::empty(paradiso::Size{4, 4});

    auto checker_board_2 = paradiso::Bitmap::from_data(
        paradiso::Size{2, 2}, 
        paradiso::RGBA::from_rgb(0x00, 0xFF, 0x00), // G
        paradiso::RGBA::from_rgb(0xFF, 0x00, 0x00), // R
        paradiso::RGBA::from_rgb(0x00, 0x00, 0xFF), // B
        paradiso::RGBA::from_rgb(0xFF, 0x00, 0xFF));// C

    auto window = paradiso::Window();

    window.set_size(paradiso::Size{.width = 1280, .height = 720})
        .set_position(paradiso::Point{.x = 100, .y = 100})
        .set_title("PardiSO")
        .set_visible(true);

    auto ctx = paradiso::Context{};

    auto sprite = paradiso::Sprite{
        .bitmap = checker_board_2
    };

    auto renderer = paradiso::Renderer{};

    auto shader = paradiso::Shader{};

    setup_shaders(shader);

    uint8_t green_slider = 0x00;
    bool want_close{false};
    int frame_counter = 10;

    window.set_keyboardcallback(
        [&](auto& w, int key, int scancode, int action, int mods) {
            if (key == 'Q' || key == 256)
                want_close = true;
            else if (key == 'A' ) {
                green_slider += 10;
            }
        });

    while (window.update([&](auto& w) -> bool {

        ctx.set_clearcolor(paradiso::RGBA::from_rgb(0xFF, green_slider, 0x00));
        ctx.set_viewport(paradiso::Rectangle{
            .size = w.client_size()
        });
        ctx.clear();

        renderer.draw(sprite, shader);

        return !want_close;
    })) {
    };

    return 0;
}