#include "Renderer.h"

#include "../Window/Window.h"

#include <stdexcept>

using namespace std;
using namespace quokka_gfx;
//--------------------------------------------------------------
/* Constructor */
Renderer::Renderer(const Window &window)
  : m_owner(window)
{
  // Create the native SDL renderer associated with the window
  m_nativeRenderer = SDL_CreateRenderer(m_owner.GetNativeWindow(), nullptr);

  if (!m_nativeRenderer)
  {
    throw std::runtime_error("Failed to create SDL renderer: " + std::string(SDL_GetError()));
  }

  // Enable VSync for the renderer to synchronize rendering with the display's refresh rate
  SDL_SetRenderVSync(m_nativeRenderer, 1);
}
//--------------------------------------------------------------
/* Default destructor */
Renderer::~Renderer()
{
  if (m_nativeRenderer)
    SDL_DestroyRenderer(m_nativeRenderer);
}
//--------------------------------------------------------------
/* Get the native SDL renderer */
SDL_Renderer *Renderer::getNativeRenderer() const noexcept
{
  return m_nativeRenderer;
}
//--------------------------------------------------------------
/* Clear the rendering target */
void Renderer::clear() const
{
  SDL_RenderClear(m_nativeRenderer);
}
//--------------------------------------------------------------
/* Present the rendered content to the window */
void Renderer::present() const
{
  SDL_RenderPresent(m_nativeRenderer);
}
//--------------------------------------------------------------
void Renderer::setDrawColor(const Color &color) const
{
  SDL_SetRenderDrawColor(m_nativeRenderer, color.r, color.g, color.b, color.a);
}
//--------------------------------------------------------------
/* Draw a line */
void Renderer::drawLine(const FPos &start, const FPos &end) const
{
  SDL_RenderLine(m_nativeRenderer, start.x, start.y, end.x, end.y);
}
//--------------------------------------------------------------
/* Draw a rectangle outline */
void Renderer::drawRect(const FPos &start, const FSize &size) const
{
  const SDL_FRect rect{ start.x, start.y, size.w, size.h };
  SDL_RenderRect(m_nativeRenderer, &rect);
}
//--------------------------------------------------------------
/* Draw a filled rectangle */
void Renderer::fillRect(const FPos &start, const FSize &size) const
{
  const SDL_FRect rect{ start.x, start.y, size.w, size.h };
  SDL_RenderFillRect(m_nativeRenderer, &rect);
}
//--------------------------------------------------------------
