const c = @import("c.zig");
const std = @import("std");
const os = std.os;
const panic = std.debug.panic;
const builtin = @import("builtin");

pub const is_on = if (builtin.mode == .ReleaseFast) c.GL_FALSE else c.GL_TRUE;

fn glDebugMessage(
    source: c.GLenum,
    typ: c.GLenum,
    id: c.GLuint,
    severity: c.GLenum,
    length: c.GLsizei,
    _message: [*c]const u8,
    user: ?*const anyopaque,
) callconv(.C) void {
    _ = id;
    _ = user;

    switch (typ) {
        c.GL_DEBUG_TYPE_ERROR,
        c.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR,
        c.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR,
        => {},
        else => return,
    }

    const message = _message[0..@as(usize, @intCast(length))];
    std.debug.print("GL Callback [{}] {} / {}: {s}\n", .{ source, typ, severity, message });
}

pub fn init() void {
    if (is_on == c.GL_TRUE) {
        c.glEnable(c.GL_DEBUG_OUTPUT);
        c.glDebugMessageCallback(glDebugMessage, null);
    }
}

pub fn assertNoError() void {
    if (is_on == c.GL_TRUE) {
        var err = c.glGetError();
        while (err != c.GL_NO_ERROR) : (err = c.glGetError()) {
            panic("GL error: {}\n", .{err});
        } else {
            return;
        }

        panic("GL Errors encountered.\n", .{err});
    }
}
