#include <stdio.h>
#include <string.h>

#include "core.h"
#include "log.h"

#include <SDL3/SDL.h>

#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif

void error_backend(const char* txt)
{
	SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Engine Error", txt, nullptr);
}

void warning_backend(const char* txt)
{
	SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Warning!", txt, nullptr);
}

//static void initializeConsole() {
//	AllocConsole(); 
//	freopen("CONOUT$", "w", stdout);
//}

int Core::ms_argc;
char** Core::ms_argv;

void Core::Init(int argc, char* argv[])
{
	ms_argc = argc;
	ms_argv = argv;

	// initialize timer
	//getSystemTimer()->init();

#ifdef WIN32
	//initializeConsole();
#endif

	Logger::Open();
}

void Core::Shutdown()
{
	Logger::Close();

	// shutdown timer
	//getSystemTimer()->shutdown();
}

void Core::Frame()
{
	//getSystemTimer()->update();
}

void Core::Error(const char* msg, ...)
{
	static char buf[2048 * 2];
	va_list args;

	va_start(args, msg);
	vsnprintf(buf, sizeof(buf), msg, args);
	va_end(args);

	Logger::Msg("ERROR! %s", buf);

	error_backend(buf);

//	__debugbreak();

#ifdef WIN32
	ExitProcess(1);
#endif // WIN32
}

void Core::Warning(const char* msg, ...)
{
	static char buf[2048 * 2];
	va_list args;

	va_start(args, msg);
	vsnprintf(buf, sizeof(buf), msg, args);
	va_end(args);

	Logger::Msg("Warning! %s", buf);
	
	warning_backend(buf);
}

bool Core::HasOption(const char* name)
{
	for (int i = 0; i < ms_argc; i++) {
		if (ms_argv[i]) {
			if (strcmp(ms_argv[i], name) == 0)
				return true;
		}
	}

	return false;
}

const char* Core::GetOptionParameter(const char* name)
{
	for (int i = 0; i < ms_argc; i++) {
		if (ms_argv[i]) {
			if (strcmp(ms_argv[i], name) == 0) {
				if (!ms_argv[i + 1]) {
					Core::Error("Commandline option %s doesn't have parameter!", name);
				} else {
					return ms_argv[i + 1];
				}
			}
		}
	}

	return nullptr;
}
