#include "Application.h"
#include "SceneManager.h"
#include "Logger.hpp"
#include <iostream>

using namespace std;

Application* Application::instance = nullptr;

Application::Application() {
	instance = this;
	debugMode = false;
	Logger::SetMaxLoggingLevel(Logger::Levels::Info);
	Logger::SetDebugMode(debugMode);
	std::cout << endl << endl << "Enter you desired world: " << endl << "(Enter filename without level number or filextension or enter 1 for default)"<< endl << "> ";
	std::string world;
	std::cin >> world;
	std::string spriteAtlas;
	if (world == "1")
	{
		world = "1level";
		spriteAtlas = "platformer-art-deluxe";
	}
	else {
		std::ostringstream oss;
		
		bool fileExist = false;
		do{
			
			oss.str("");
			oss << world << "1.json";
			ifstream f(oss.str());
			if (f.good())
			{
				fileExist = true;
			}
			else {
				std::cout << endl << endl << "Filename Not Found, please enter correct file name" << endl << "(Write 0 to exit application)" << endl << "> ";
				world = "";
				cin >> world;
				if (world == "0")
				{
					exit(0);
				}
			}
		} while (!fileExist);
		
		std::cout << endl << endl << "Enter name of Spriteatlas(Without file extension): " << endl << "(File must be a png and have accomponing json file)" << endl << "> ";
		std::cin >> spriteAtlas;
		
		bool atlasExist = false;
		do
		{
			oss.str("");
			oss << spriteAtlas << ".json";
			ifstream f(oss.str());
			if (f.good())
			{
				atlasExist = true;
			}
			else {
				std::cout << endl << endl << "Filename Not Found, please enter correct file name" << endl << "(Write 0 to exit application)" << endl << "> ";
				spriteAtlas = "";
				cin >> spriteAtlas;
				if (world == "0")
				{
					exit(0);
				}
			}
		} while (!atlasExist);
	}
	isApplicationRunning = true;
	try {
		SceneManager::SceneManager(world, spriteAtlas);
	}
	catch (const std::exception& e) {
		std::string errmsg = e.what();
		Logger::Error("Unhandled exception in Application: " + errmsg);
	}
	catch (const char* msg) {
		std::string errmsg = msg;
		Logger::Error("Unhandled exception in Application: " + errmsg);
	}
	catch (...) {
		Logger::Error("Unknown exeption in Application.");
	}
}

Application * Application::GetInstance() {
	if (instance == nullptr) {
		new Application();
	}
	return instance;
}

void Application::quit() {
	Application::~Application();
}
