#include "SceneManager.h"
#include "Logger.hpp"
#include "rapidjson/rapidjson.h"
#include "rapidjson/document.h"
#include "rapidjson/istreamwrapper.h"
#include <string>
#include <iostream>
#include <fstream>

using namespace rapidjson;
using namespace std;

//const glm::vec2 SceneManager::windowSize(1920, 1080);
SceneManager* SceneManager::instance = nullptr;

void SceneManager::onKey(SDL_Event & event) {
	if (event.key.keysym.sym == SDLK_ESCAPE)
	{
		exit(0);
	}
	currentScene.KeyEvent(event);
}

SceneManager::SceneManager(std::string levelPackage, std::string spriteAtlas) {
	if (instance == nullptr) {
		instance = this;
	}
	else {
		return;
	}
	//Sets fullscreen
	isFullscreen = false;
	if (isFullscreen)
	{
		windowSize = glm::vec2(1920, 1080);
	}
	else
	{
		windowSize = glm::vec2(800, 600);
	}
	
	r.setWindowSize(windowSize);
	bool useVsync = true;
	r.init(SDL_INIT_EVERYTHING, SDL_WINDOW_OPENGL, useVsync);

	backgroundColor = glm::vec4(0.6, 0.6, 1, 1);
	
	instance = this;		
	r.keyEvent = [&](SDL_Event& e) {
		onKey(e);
	};
	r.frameUpdate = [&](float deltaTime) {
		update(deltaTime);
	};
	r.frameRender = std::bind(&SceneManager::render, this);

	LoadScene(levelPackage,spriteAtlas);
	// start game loop
	
	r.startEventLoop();
}

SceneManager * SceneManager::GetInstance() {
	if (instance == nullptr) {
		SceneManager("1","platformer-art-deluxe");
	}
	return instance;
}

void SceneManager::LoadScene(std::string worldFile, std::string spriteAtlas) {
	Logger::Info("Loading scene " + worldFile + " with SpriteAtlas: " + spriteAtlas);
	std::string jsonFile = spriteAtlas + ".json";
	std::string pngFile = spriteAtlas + ".png";
	atlas = sre::SpriteAtlas::create(jsonFile, pngFile);
	currentScene.LoadLevel(worldFile);

	
}

void SceneManager::update(float deltaTime) {
	currentScene.update(deltaTime);
}

void SceneManager::render() {
	currentScene.Draw();
}

Scene * SceneManager::GetCurrentScene() {
	return &currentScene;
}

void SceneManager::CurrentLevelOver() {
	currentScene.LevelOver();
}
