#include <iostream>
#include <string>
#include <SDL.h>
#include <SDL_image.h>
#include <GL/glew.h>

#include "Reassembly2.h"

using namespace std;

const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
static SDL_Window* gWindow = NULL;
static SDL_GLContext glcontext;

void dispose();
bool initSDL();

int main(int argc, char *argv[]) {
	//Init SDL_Window, SDL_Surface, SDL_Renderer
	if(!initSDL()) {
		dispose();
		return 1;
	}

	//While application is running
	bool quit = false;
	SDL_Event e;
	Reassembly2 resA(gWindow);
	resA.create();
	unsigned int lastTime = SDL_GetTicks(), currentTime, elapsedTime;
	while( !quit ) {
		currentTime = SDL_GetTicks();
		elapsedTime = currentTime - lastTime;
		lastTime = currentTime;
		if(SDL_PollEvent(&e) != 0) {
			if(e.type == SDL_QUIT) {
				quit = true;
				break;
			}
			resA.loop(&e,elapsedTime);
		} else {
			resA.loop(NULL,elapsedTime);
		}

	}

	dispose();
	return 0;
}

bool initSDL() {
	//Init SDL
	if(SDL_Init(SDL_INIT_VIDEO) < 0 ) {
		cout << "SDL could not initialize! SDL_Error: " << SDL_GetError() << endl;
		return false;
	} 
	//Init Window
	gWindow = SDL_CreateWindow( "SDL TEST", SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_OPENGL);
	if( gWindow == NULL) {
		cout << "Window could not be created! SDL_Error: " << SDL_GetError() << endl;
		return false;
	} 
	//Mask deprectated functions
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	//Init OpenGL Renderer
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	glcontext = SDL_GL_CreateContext(gWindow);
	if(glcontext == NULL) {
		cout << "Could not create OpenGL Context: " << SDL_GetError() << endl;
		return false;
	}
	//Init GLEW
	glewExperimental = GL_TRUE;
	GLenum err = glewInit();
	if(GLEW_OK != err) {
		cout << "Init of Glew failed: " << glewGetErrorString(err) << endl;
		return false;
	}
	return true;
}

void dispose() {
	SDL_GL_DeleteContext(glcontext);
	SDL_DestroyWindow( gWindow );
	SDL_Quit();
}
