const rl = @import("c.zig").rl;

const FPS_CAPTURE_FRAMES_COUNT : i32 = 30;      // 30 captures
const FPS_AVERAGE_TIME_SECONDS : f32 = 0.5;     // 500 milliseconds
const FPS_STEP                 : f32 = (FPS_AVERAGE_TIME_SECONDS / FPS_CAPTURE_FRAMES_COUNT);

var index   : u32 = 0;
var history : [FPS_CAPTURE_FRAMES_COUNT]f32 = .{0} ** FPS_CAPTURE_FRAMES_COUNT;
var average : f32 = 0;
var last    : f32 = 0;

pub fn drawFPS(posX : i32, posY : i32, fpsFrame : f32) void {
    var color : rl.Color = rl.LIME;                // Good FPS
    const fps : i32 = getFPS(fpsFrame);

    if ((fps < 30) and (fps >= 15)) {color = rl.ORANGE;}  // Warning FPS
    else if (fps < 15) color = rl.RED;             // Low FPS

    rl.DrawText(rl.TextFormat("%2i FPS", fps), posX, posY, 20, color);
}

pub fn getFPS(fpsFrame : f32) i32 {
    var fps : i32 = 0;

    if (fpsFrame == 0) return 0;

    if ((rl.GetTime() - last) > FPS_STEP)
    {
        last = @floatCast(rl.GetTime());
        index = (index + 1) % FPS_CAPTURE_FRAMES_COUNT;
        average -= history[index];
        history[index] = fpsFrame / FPS_CAPTURE_FRAMES_COUNT;
        average += history[index];
    }

    fps = @intFromFloat(1.0 / average);

    return fps;
}
