#include "display.hpp"

#include <glm/vec2.hpp>

namespace game::util::display
{
  namespace
  {
    SDL_Window* window{};
    bool isFullscreen{};
    glm::ivec2 windowedPosition{};
    glm::ivec2 windowedSize{};
  }

  void init(SDL_Window* value)
  {
    window = value;
    if (!window) return;

    SDL_GetWindowPosition(window, &windowedPosition.x, &windowedPosition.y);
    SDL_GetWindowSize(window, &windowedSize.x, &windowedSize.y);
  }

  bool fullscreen_get()
  {
    return isFullscreen;
  }

  void fullscreen_set(bool enabled)
  {
    if (!window || enabled == isFullscreen) return;

    if (enabled)
    {
      SDL_GetWindowPosition(window, &windowedPosition.x, &windowedPosition.y);
      SDL_GetWindowSize(window, &windowedSize.x, &windowedSize.y);

      auto displayID = SDL_GetDisplayForWindow(window);
      if (!displayID) displayID = SDL_GetPrimaryDisplay();

      if (const auto* mode = SDL_GetDesktopDisplayMode(displayID))
      {
        SDL_SetWindowFullscreenMode(window, nullptr);
        SDL_SetWindowSize(window, mode->w, mode->h);
      }

      SDL_SetWindowFullscreen(window, true);
      isFullscreen = true;
      return;
    }

    SDL_SetWindowFullscreen(window, false);
    SDL_SetWindowSize(window, windowedSize.x, windowedSize.y);
    SDL_SetWindowPosition(window, windowedPosition.x, windowedPosition.y);
    isFullscreen = false;
  }

  void fullscreen_toggle()
  {
    fullscreen_set(!isFullscreen);
  }
}
