#include "Application.h"

#include <SDL3/SDL.h>
#include <algorithm>

using namespace std;
using namespace quokka_gfx;
//--------------------------------------------------------------
/* Default constructor */
Application::Application()
  : m_eventManager(*this)
{
  // Initialize SDL context
  m_sdlContext = SDLContext::GetContext();
}
//--------------------------------------------------------------
/* Get the WindowManager instance */
WindowManager *Application::GetWindowManager() noexcept
{
  return &m_windowManager;
}
//--------------------------------------------------------------
/* Start the main event loop */
void Application::Run() const
{
  // Main loop
  bool     running  = true;
  uint64_t lastTime = SDL_GetTicksNS();

  while (running && m_windowManager.HasAnyWindow())
  {
    // Calculate delta time
    const uint64_t currentTime = SDL_GetTicksNS();
    float          dt          = static_cast<float>(currentTime - lastTime) / 1e9f;     // Convert nanoseconds to seconds
    lastTime                   = currentTime;
    dt                         = std::max(dt, 0.00001f);     // Avoid zero or negative delta time

    // Poll and process events
    const auto result = m_eventManager.ProcessEvents();
    if (result == EventManager::PollingResult::Quit)
      running = false;

    // Update and Render all windows
    m_windowManager.Update(dt);
    m_windowManager.Render();
  }
}
//--------------------------------------------------------------
