#include <climits>
#include <iostream>
#include <string>

#include "window.hpp"

//------------------------------------------------------------------------------
CWindow::CWindow(const string &aCaption, const CSettings &aSettings)
//------------------------------------------------------------------------------
    : lFreeze(aSettings.Freeze())
{
  if (SDL_Init(SDL_INIT_VIDEO) < 0)
    throw string("SDL_Init() hívása sikertelen: ") + SDL_GetError();

  SDL_WM_SetCaption(aCaption.c_str(), NULL);
  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, true);

  int flags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER | SDL_HWSURFACE | SDL_HWACCEL;
  if (aSettings.Fullscreen())
  {
    flags |= SDL_FULLSCREEN;
    SDL_ShowCursor(SDL_DISABLE);
  }
  lSurface = SDL_SetVideoMode(aSettings.Width(), aSettings.Height(), 32, flags);

  if (!lSurface)
    throw string("SDL_SetVideoMode() hívása sikertelen: ") + SDL_GetError();

  if (!SDL_GL_LoadLibrary(NULL))
    throw string("SDL_GL_LoadLibrary() hívása sikertelen: ") + SDL_GetError();

  if (!InitGL())
    throw string("InitGL() hívása sikertelen");

  lRenderer = new CRenderer(aSettings);
}

//------------------------------------------------------------------------------
CWindow::~CWindow()
//------------------------------------------------------------------------------
{
  SDL_Quit();
}

//------------------------------------------------------------------------------
void CWindow::Run()
//------------------------------------------------------------------------------
{
  SDL_Event event;
  Uint8 *keys;
  Uint32 timeStart, timeNow;
  int frames;

  lQuit = false;
  timeStart = timeNow = SDL_GetTicks();
  frames = 0;
  lMinFPS = INT_MAX;
  lMaxFPS = 0;
  lTotalFrames = 0;
  lTotalSeconds = 0;

  if (lFreeze)
    lRenderer->Draw(lFreeze);

  while (!lQuit)
  {
    // --- Események ---
    SDL_PollEvent(&event);

    if (event.type == SDL_QUIT)
    {
      lQuit = true;
      break;
    }

    // --- Billentyűzet ---
    keys = SDL_GetKeyState(NULL);

    if (keys[SDLK_ESCAPE])
      lQuit = true;

    if (lFreeze && keys[SDLK_SPACE])
      lRenderer->Draw(lFreeze);

    // --- Rajzolás ---
    if (!lFreeze)
    {
      lRenderer->Draw(timeNow / 1000.0);
      ++frames;

      // --- Sebesség ---
      timeNow = SDL_GetTicks();
      if (timeNow - timeStart >= 1000)
      {
        cout << frames << " FPS" << endl << flush;

        if (frames < lMinFPS)
          lMinFPS = frames;
        if (frames > lMaxFPS)
          lMaxFPS = frames;
        lTotalFrames += frames;
        ++lTotalSeconds;

        timeStart = timeNow;
        frames = 0;
      }
    }
  }

  if (!lFreeze)
  {
    cout << "Min.: " << lMinFPS << " FPS" << endl;
    cout << "Max.: " << lMaxFPS << " FPS" << endl;
    cout << "Átl.: " << (static_cast<float>(lTotalFrames) / lTotalSeconds) << " FPS" << endl << flush;
  }
}
