#include "Application.h"

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

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;
  auto lastTime = std::chrono::nanoseconds(SDL_GetTicksNS());

  while (running && m_windowManager.HasAnyWindow())
  {
    // Calculate delta time
    const auto currentTime = std::chrono::nanoseconds(SDL_GetTicksNS());
    const auto dt          = currentTime - lastTime;
    lastTime               = currentTime;

    // 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();
  }
}
//--------------------------------------------------------------
