/********************\
|  Copyright 2024,   |
|       Ulysse Cura  |
\********************/

////////////////////////////////////////
//                                    //
//   Main, gère la boucle principale. //
//                                    //
////////////////////////////////////////

#include <iostream> // cerr
#include <stdexcept> // exception
#include "Game.hpp" // Game definition

using std::cerr, std::exception;

Game *game {nullptr};

int main()
{
    // Pour limiter les FPS
    const int FPS {60};
    const float FRAME_DELAY {1000.0f / FPS};

    Uint32 frameStart;
    int frameTime;

    game = new Game();

    try
    {
        game->Init();
    }
    catch(exception const &e)
    {
        cerr << e.what();
        delete game;
        return EXIT_FAILURE;
    }

    while(game->Running())
    {
        frameStart = SDL_GetTicks();

        game->HandleEvents();
        try
        {
            game->Update();
        }
        catch(exception const &e)
        {
            cerr << e.what();
            delete game;
            return EXIT_FAILURE;
        }
        game->Render();

        frameTime = SDL_GetTicks() - frameStart;

        if(static_cast<float>(frameTime) < FRAME_DELAY)
        {
            SDL_Delay(static_cast<Uint32>(FRAME_DELAY - static_cast<float>(frameTime)));
        }
#ifdef DEBUG_MODE
        else
        {
            cerr << 1000 / frameTime << " FPS\n";
        }
#endif
    }

    delete game;

    return EXIT_SUCCESS;
}