//
// Created by vfs on 1/28/26.
//

#include <cstdint>
#include <raylib.h>

namespace misc {

    const int32_t FPS_CAPTURE_FRAMES_COUNT = 30;      // 30 captures
    const float   FPS_AVERAGE_TIME_SECONDS = 0.5;     // 500 milliseconds
    const float   FPS_STEP                 = (FPS_AVERAGE_TIME_SECONDS / FPS_CAPTURE_FRAMES_COUNT);

    uint32_t index = 0;
    float history[FPS_CAPTURE_FRAMES_COUNT] = {};
    float average = 0;
    float last    = 0;

    int32_t getFPS(float fpsFrame) {
        int32_t fps = 0;

        // if we reset the window, reset the FPS info
        // if (frame == 0)
        // {
        //     average = 0;
        //     last = 0;
        //     index = 0;

        //     for (0..FPS_CAPTURE_FRAMES_COUNT) |i| history[i] = 0;
        // }

        if (fpsFrame == 0) return 0;

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

        fps = 1.0 / average;

        return fps;
    }

    void drawFPS(int32_t posX, int32_t posY, float fpsFrame) {
        Color color = LIME;                         // Good FPS
        const int32_t fps = getFPS(fpsFrame);

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

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

}
