#include <SDL.h>
#include <SDL_ttf.h>
#include <time.h>
#include <assert.h>
#include "InvControls.h"
#include "InvParams.h"
#include "TetriminoManager.h"
#include "TetrisBoard.h"

//Tetris
//by Brian MacIntosh for UCI VGDC
//
// 2/8/13 v0.1 Preliminary

bool gameRunning = true;

//Screen drawing surface
SDL_Surface* surface;

//Game structures
TetriminoManager* manager;
TetrisBoard* board;


void quit()
{
	gameRunning = false;
}


/*
Handles SDL input and device events
*/
void handleEvent(SDL_Event* ev)
{
	if (ev->type == SDL_QUIT)
		gameRunning = false;
	else
		_controls_handleEvent(ev);
}


/*
Loads game structures
*/
void initialize()
{
	TetriminoManager::Init();
	board = new TetrisBoard();
}


/*
Handles game logic update each frame
*/
void update(double elapsedSeconds)
{
	if (keyPressed(SDLK_ESCAPE)) quit();

	board->update(elapsedSeconds);
}


/*
Render game to main surface
*/
void draw()
{
	SDL_Rect rect;
	rect.x = rect.y = 0;
	rect.w = screenWidth;
	rect.h = screenHeight;
	SDL_FillRect(surface, &rect, 0xFF000000);

	board->draw(surface, 100, 100);
	TetriminoManager::drawQueue(surface, 600, 100);

	SDL_Flip(surface);
}


/*
Removes game structures
*/
void cleanup()
{
	TetriminoManager::Deinit();
	delete board;
}


/*
Entry point
*/
int main(int argc, char* argv[])
{
	srand(time(0));

	//Load SDL
	if(SDL_Init(SDL_INIT_EVERYTHING) < 0) return 1;
	surface = SDL_SetVideoMode(
		screenWidth, screenHeight, screenDepth,
		(fullscreen ? SDL_FULLSCREEN : 0));
	assert(surface != NULL);

	//Load TTF
	assert(TTF_Init() >= 0);

	//Config window
	SDL_WM_SetCaption(windowBarName, "");

	//Load game
	initialize();

	//Initialize loop
	clock_t ticksPerFrame = CLOCKS_PER_SEC / targetFrameRate;
	clock_t lastUpdate = clock();
	clock_t lastDraw = 0;

	//Game loop
	while (gameRunning)
	{
		//Handle events
		_controls_step();
		SDL_Event ev;
		while (SDL_PollEvent(&ev)) handleEvent(&ev);

		//Update logic
		clock_t thisUpdate = lastUpdate;
		lastUpdate = clock();
		update((lastUpdate - thisUpdate) / (1.0 * CLOCKS_PER_SEC));

		//Draw to screen
		if (targetFrameRate == -1 || clock() - lastDraw >= ticksPerFrame)
		{
			lastDraw = clock();
			draw();
		}
	}

	//Free surfaces
	cleanup();

	SDL_Quit();

	return 0;
}