#include "glad/gl.h"
#include <string>

using error = std::string;

error loadShader(int t, const char* source, int* shader)
{
    // Create
    int s;
    s = glCreateShader(t);
    // Load source
    glShaderSource(s, 1, &source, NULL);
    // Compile
    glCompileShader(s);
    // Check status
    int ok;
    glGetShaderiv(s, GL_COMPILE_STATUS, &ok);
    if (!ok) {
        return "failed to compile shader";
    }

    *shader = s;
    return "";
}

error loadProgram(const char* vertexSource, const char* fragmentSource, int* program)
{
    error err;

    // Vertex shader
    int vertexShader;
    err = loadShader(GL_VERTEX_SHADER, vertexSource, &vertexShader);
    if (err != "") {
        return err;
    }

    // Fragment shader
    int fragmentShader;
    err = loadShader(GL_FRAGMENT_SHADER, fragmentSource, &fragmentShader);
    if (err != "") {
        return err;
    }

    // Shader program
    int shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);

    // Check status
    int ok;
    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &ok);
    if (!ok) {
        return "failed to link program";
    }

    // Clean no longer needed shaders
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);

    *program = shaderProgram;
    return "";
}