#include "LevelManager.h"
#include "Logger.hpp"
#include "Box2D/Dynamics/b2World.h"
#include "Application.h"
#include <sys/stat.h>

using namespace std;
using namespace rapidjson;

LevelManager::LevelManager() {
	Logger::Debug("Level Manager Contructor");
}

void LevelManager::Start(
	Event<void(float)>* Update,
	Event<void(sre::SpriteBatch::SpriteBatchBuilder&)>* DrawScene,
	Event<void()>* PhysicsStep,
	Event<void(SDL_Event&)>* keyEvent,
	std::shared_ptr<b2World> physicsWorld, std::string startingLevel) {
	defaultLevelName = startingLevel + "1.json";
	NextLevel(Update, DrawScene, PhysicsStep, keyEvent, physicsWorld);
	Logger::Debug("STOP!");
}

void LevelManager::NextLevel(
	Event<void(float)>* Update,
	Event<void(sre::SpriteBatch::SpriteBatchBuilder&)>* DrawScene,
	Event<void()>* PhysicsStep,
	Event<void(SDL_Event&)>* keyEvent,
	std::shared_ptr<b2World> physicsWorld) {	
	string levelName = "";
	if (currentLevel.levelObj == nullptr) {
		levelName = defaultLevelName;
	}
	else {
		std::vector<std::shared_ptr<GameObject>> deleteObjects; 
		for (auto& go : currentLevel.levelObjects) {
			if (go == nullptr) {
				break;
			}
			if (go->IsActive()) {
				go->ToggleActive();
				deleteObjects.push_back(go);
			}
		}
		currentLevel.cameraObject->ToggleActive();		
		
		for (int i = 0; i < deleteObjects.size(); i++) {
			currentLevel.levelObjects[i].reset();
		}
		
		std::ostringstream oss;
		//The name of the tile has to be tile + ID , otherwise this will not work
		oss << "1level" << currentLevel.levelObj->getId() + 1 << ".json";
		//struct stat buffer;
		ifstream f(oss.str());
		if (f.good())
		{
			levelName = oss.str();
		}
		else
		{
			levelName = defaultLevelName;
		}
	}
	LevelBuilder lb = *new LevelBuilder(Update, DrawScene, PhysicsStep, keyEvent, physicsWorld);
	currentLevel = lb.BuildFromFile(levelName);
}

void LevelManager::DeleteLevel() {
	std::vector<std::shared_ptr<GameObject>> deleteObjects;
	for (auto& go : currentLevel.levelObjects) {
		if (go->IsActive()) {
			go->ToggleActive();
			deleteObjects.push_back(go);
		}
	}

	for (int i = 0; i < deleteObjects.size(); i++) {
		currentLevel.levelObjects[i].reset();
	}
}
