#include <SDL.h>
#include <SDL_events.h>
#include <SDL_image.h>

#include <iostream>

#include "gameplay/game.h"
#include "utility/logger.h"

int main(int argc, char* args[])
{
	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
    LOG(ERROR, "Failed to initialize SDL!", NULL);
		return -1;
  }
	if (IMG_Init(IMG_INIT_PNG) < 0) {
    LOG(ERROR, "Could not initialize png library", NULL);
		return -1;
  }

	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

	Game* game = new Game();
	if (!game->init())
	{
    LOG(ERROR, "Failed to init game!", NULL);
		return -1;
	}

	if (!game->loadDebugScene())
	{
    LOG(ERROR, "Failed to load debug scene!", NULL);
		return -1;
	}

	SDL_Event e;
	Uint64 lastCounter = SDL_GetPerformanceCounter();
	double freq = static_cast<double>(SDL_GetPerformanceFrequency());
	while (game->getGameState() & GAME_RUNNING)
	{
		Uint64 curCounter = SDL_GetPerformanceCounter();
		double deltaTime = ((curCounter - lastCounter) / freq);
		deltaTime = (deltaTime < 1.0) ? deltaTime : 1.0;
		while (SDL_PollEvent(&e)) {
			if (e.type == SDL_QUIT)
				game->quit();

			game->captureInput(e);
		}
		game->executeInputs();

		game->render();
		game->update(deltaTime);
		lastCounter = curCounter;

	}

	delete game;
	IMG_Quit();
	SDL_Quit();

	return 0;
}
