#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <string>

// Define a static function to print a string to the console
template <class T>
static void print(T t)
{
    std::cout << t << std::endl;
}

// Function to compile a shader of a given type (vertex or fragment)
static int compileShader(unsigned int type, const std::string& source)
{
    // Create a shader object and get its ID
    unsigned int id = glCreateShader(type);
    std::cout << "Shader id:" << id << std::endl;

    // Convert the shader source code from std::string to C-string
    const char* src = source.c_str();

    // Associate the source code with the shader object
    glShaderSource(id, 1, &src, nullptr);

    // Compile the shader
    glCompileShader(id);

    // Check if the compilation was successful
    int result;
    glGetShaderiv(id, GL_COMPILE_STATUS, &result);
    if (result == GL_FALSE)
    {
        // If compilation failed, retrieve the error message length
        int length;
        glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length);

        // Allocate space for the error message
        char* message = (char*)alloca(length * sizeof(char));

        // Get the error message
        glGetShaderInfoLog(id, length, &length, message);
        std::cout << "Failed to compile shader: " <<
            (type == GL_VERTEX_SHADER ? "Vertex" : "Fragment") << " shader" << std::endl;
        print(message);

        // Delete the shader object as it failed to compile
        glDeleteShader(id);
        return 0;
    }

    return id;
}

// Function to create a shader program by linking a vertex and fragment shader
static int CreateAShader(const std::string& vertexShader, const std::string& fragmentShader)
{
    // Create a shader program and get its ID
    unsigned int program = glCreateProgram();

    // Compile the vertex shader
    unsigned int vs = compileShader(GL_VERTEX_SHADER, vertexShader);

    // Compile the fragment shader
    unsigned int fs = compileShader(GL_FRAGMENT_SHADER, fragmentShader);

    // Attach the compiled shaders to the program
    glAttachShader(program, vs);
    glAttachShader(program, fs);

    // Link the shaders together into a complete program
    glLinkProgram(program);

    // Validate the linked program to ensure it's usable
    glValidateProgram(program);

    return program;
}

int main() {
    // Initialize GLFW to create a window and manage the OpenGL context
    if (!glfwInit()) {
        print("Failed to initialize GLFW");
        return -1;
    }

    // Set GLFW window hints for OpenGL version and profile
    // These lines can specify which version of OpenGL to use
    // glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Set major version to 3
    // glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Set minor version to 3
    // glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Set profile to core profile

    // Create a windowed mode window and its OpenGL context
    GLFWwindow* window = glfwCreateWindow(800, 600, "GLFW Window", NULL, NULL);
    if (!window) {
        std::cerr << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }

    // Make the window's OpenGL context current on the calling thread
    glfwMakeContextCurrent(window);

    // Initialize GLEW to manage OpenGL function pointers and extensions
    glewExperimental = GL_TRUE; // Enable modern techniques for managing OpenGL functionality
    if (glewInit() != GLEW_OK) {
        std::cerr << "Failed to initialize GLEW" << std::endl;
        return -1;
    }

    // Print the GLEW version to the console
    std::cout << "GLEW VERSION:" << glGetString(GL_VERSION) << std::endl;

    // Define an array of vertex positions for a single triangle
    float positions[6] = { -0.5f, -0.5f, 0.0f, 0.5f, 0.5f, -0.5f };

    // Calculate the total size of the vertex data in bytes
    int totalSize = std::size(positions) * sizeof(positions);

    // Create a buffer on the GPU and get its ID
    unsigned int buffer;
    glGenBuffers(1, &buffer);

    // Bind the buffer as an array buffer to upload vertex data
    glBindBuffer(GL_ARRAY_BUFFER, buffer);

    // Upload the vertex data to the GPU buffer
    glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), positions, GL_STATIC_DRAW);

    // Enable the first attribute (position) in the shader
    glEnableVertexAttribArray(0);

    // Specify how OpenGL should interpret the vertex data
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0);

    // Unbind the array buffer to avoid accidental modification
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    // Define the source code for the vertex shader
    std::string vertexShader =
        "#version 330 core \n"
        "\n"
        "layout(location = 0) in vec4 position;"
        "\n"
        "void main()"
        "{\n"
        "   gl_Position = position;\n"
        "}\n";

    // Define the source code for the fragment shader
    std::string fragmentShader =
        "#version 330 core \n"
        "\n"
        "layout(location = 0) out vec4 color;"
        "\n"
        "void main()"
        "{\n"
        "   color = vec4(1.0,0.0,0.0,1.0);\n"
        "}\n";

    // Create and compile the shader program from the vertex and fragment shaders
    unsigned int shader = CreateAShader(vertexShader, fragmentShader);

    // Use the compiled shader program for rendering
    glUseProgram(shader);

    // Main rendering loop
    while (!glfwWindowShouldClose(window)) {
        // Clear the color buffer to prepare for a new frame
        glClear(GL_COLOR_BUFFER_BIT);

        // Draw the triangle using the vertex data and the shader program
        glDrawArrays(GL_TRIANGLES, 0, 3);

        // Swap the front and back buffers (double buffering)
        glfwSwapBuffers(window);

        // Poll for and process events (keyboard, mouse, etc.)
        glfwPollEvents();
    }

    // Delete the shader program after we're done using it
    glDeleteProgram(shader);

    // Destroy the window and terminate GLFW
    glfwDestroyWindow(window);
    glfwTerminate();

    return 0;
}
