#include "Game.h"
#include "Input.h"
#include "Collision_Manager.h"
#include "Sound_Manager.h"
#include "Rewind_Manager.h"

Game::Game() : mRoom(GlobalProperties::ROOM_SIZE)
{
	Init();
}

void Game::Init()
{
	Sounds::PlayLooping(Sounds::BackgroundMusic); // Start up that pumping music!
	mControls.Init();

	bool createWall = true; // If false, will make a stack

	if (createWall)
	{
		// Create wall with bricks
		float xSpace = 2 * mBricks[0].GetCollider().GetBoundsMax().x + 0.01;
		float ySpace = 0.1f;
		int wallWidth = 11;
		float xOffset = -8.5f;
		float yOffset = -7.0f;
		
		for (int i = 0; i < GlobalProperties::BRICK_COUNT; ++i)
			mBricks[i].SetPosition(glm::vec3(xSpace*(i%wallWidth) + xOffset, ySpace*i+yOffset, 0));
	}
	else
	{
		// Create stack of bricks
		for (int i = 0; i < GlobalProperties::BRICK_COUNT; ++i)
			mBricks[i].SetPosition(glm::vec3(0.0f, i*1.5-8.5f, 0.0f));
	}

	Rewind::RewindManager::I().Init(); // This is done last, so that it can get the objects' start positions
}
void Game::UpdateObjects()
{	
	for (int i = 0; i < GlobalProperties::BRICK_COUNT; ++i)
		mBricks[i].Update();
	mBullet.Update();
}

void Game::RenderObjects()
{
	for (int i = 0; i < GlobalProperties::BRICK_COUNT; ++i)
		mBricks[i].UpdateBindRender();
	mBullet.UpdateBindRender();
	mRoom.DrawGroup();

	mControls.Print(GlobalProperties::CONTROLS_TEXT, 10, 570, 16);

	#ifdef USE_OCTREE
	CollisionManager::I().DrawOctree();
	#endif
}

void Game::Update()
{
	Rewind::RewindManager::I().Update();

	if (!Rewind::RewindManager::I().IsRewinding()) // Don't update gravity, colisions, or movement when rewinding
	{
		UpdateInput();
		CollisionManager::I().ApplyGravityAll();
		UpdateObjects();
		CollisionManager::I().CheckForCollisionsAll();
	}

	RenderObjects();
}

void Game::UpdateInput()
{
	Input::InputManager& im = Input::InputManager::I();

	if (im.GetLMouseButtonKeyStateDown())
		mBullet.Shoot();
}

void Game::CleanUp()
{
	for (int i = 0; i < GlobalProperties::BRICK_COUNT; ++i)
		mBricks[i].CleanUp();

	mBullet.CleanUp();
	mRoom.CleanUp();
	mControls.CleanUp();
}