/*
 * GameEngine.cpp
 *
 *  Created on: 12 dec 2011
 *      Author: Reii
 */

#include "SDL/SDL.h"
#include "GameEngine.h"
#include "Globals.h"
#include "Enemy.h"

void GameEngine::addSprite(Sprite* sprite){
	gameobjects.push_back(sprite);
}

std::vector<Sprite*> GameEngine::getGameobjects(){
	return gameobjects;
}

void GameEngine::clearEngine(){
	std::vector<Sprite*>::iterator iter;
	for(iter = gameobjects.begin() ; iter != gameobjects.end();){
		delete *iter;
		iter = gameobjects.erase(iter);
	}
}

void GameEngine::initEngine(){

	int startTicks = SDL_GetTicks();

	SDL_Event event;
	while(SDL_PollEvent(&event)){
		switch(event.type){
		case SDL_QUIT:
			globals.Quit();
			globals.quitProgram();
			break;

		case SDL_KEYDOWN:
			switch(event.key.keysym.sym){
			case SDLK_ESCAPE:
				globals.Quit();
				globals.setMenu("Images/Menu.bmp");
				break;

			default:
				for(unsigned int i=0 ; i < gameobjects.size() ; i++){
					gameobjects[i]->keyDown(event.key.keysym.sym);
				}
				break;
			}
			break;

		case SDL_KEYUP:
			for(unsigned int i=0; i < gameobjects.size() ; i++){
				gameobjects[i]->keyUp(event.key.keysym.sym);
			}
			break;

		case SDL_MOUSEBUTTONDOWN:
			for(unsigned int i=0; i < gameobjects.size() ; i++){
				gameobjects[i]->mouseDown(event.button.x, event.button.y);
			}
			break;
		case SDL_MOUSEBUTTONUP:
			for(unsigned int i=0; i < gameobjects.size() ; i++){
				gameobjects[i]->mouseUp(event.button.x, event.button.y);
			}
			break;

		case SDL_MOUSEMOTION:
			for(unsigned int i=0; i < gameobjects.size() ; i++){
				gameobjects[i]->mouseMoved(event.button.x, event.button.y);
			}
			break;

		}//Switch

	}//While (SLD_PollEvent)

	Uint32 bgColor = SDL_MapRGB(globals.getScreen()->format,125,125,125);
	SDL_FillRect(globals.getScreen(),NULL,bgColor);

	for(unsigned int i =0; i < gameobjects.size() ; i++){
		gameobjects[i]->tick(gameobjects);
	}
	for(unsigned int i =0; i < gameobjects.size() ; i++){
		gameobjects[i]->draw();
	}

	SDL_Flip(globals.getScreen());

	int endTicks = SDL_GetTicks();

	if(endTicks - startTicks < 1000 / globals.getFPS()){
		SDL_Delay( ( 1000 / globals.getFPS()) - (endTicks - startTicks));
	}

}// void GameEngine::initEngine()



