#include "CContext.hpp"

bool CContext::m_screenSaver = false;

void CContext::init(unsigned int sdlFlags, unsigned int imageFlags) {
	// Log initialisation.
	initLog();
	DEBUG_LOG(trace, "Kernel", "Context", "Log initialized!")

	// SDL Initialization.
	DEBUG_LOG(trace, "Kernel", "Context", "SDL initialization...")
	if (SDL_Init(sdlFlags) < 0) {
		SDL_Quit();
		HandleException(CLibException(std::string("Unable to initialize SDL: ") + SDL_GetError()), true);
	}
	DEBUG_LOG(trace, "Kernel", "Context", "SDL initialized!")


	// SDL_Image Initialization.
	int initted = IMG_Init(imageFlags);
	DEBUG_LOG(trace, "Kernel", "Context", "SDL_Image initialization...")
	if ((initted & imageFlags) != imageFlags) {
		HandleException(CLibException(std::string("Unable to initialize SDL Image: ") + IMG_GetError()), true);
	}
	DEBUG_LOG(trace, "Kernel", "Context", "SDL_Image initialized!")

	// SDL_TTF Initialization.
	DEBUG_LOG(trace, "Kernel", "Context", "SDL_TTF initialization...")
	if (TTF_Init() == -1) {
		HandleException(CLibException(std::string("Unable to initialize SDL TTF: ") + TTF_GetError()), true);
	}
	DEBUG_LOG(trace, "Kernel", "Context", "SDL_TTF initialized!")
}

bool CContext::isScreenSaverEnable(void) {
	return m_screenSaver;
}

void CContext::setScreenSaverEnable(bool newScreenSaver) {
	m_screenSaver = newScreenSaver;
	if (m_screenSaver) {
		SDL_EnableScreenSaver();
	}
	else {
		SDL_DisableScreenSaver();
	}
}

void CContext::quit(void) {
	TTF_Quit();
	IMG_Quit();
	SDL_Quit();
}

void CContext::initLog(void) {
	static const std::string COMMON_FMT("[%TimeStamp%][%Severity%]%Message%");

	boost::log::register_simple_formatter_factory< boost::log::trivial::severity_level, char >("Severity");

	// Output message to console.
	boost::log::add_console_log(
		std::cout,
		boost::log::keywords::format = COMMON_FMT,
		boost::log::keywords::auto_flush = true
	);

	// Output message to file, rotates when file reached 1mb or at midnight every day. Each log file
	// is capped at 1mb and total is 50mb.
	boost::log::add_file_log(
		boost::log::keywords::file_name = LOG_FILE,
		boost::log::keywords::rotation_size = LOG_ROTATION_SIZE,
		boost::log::keywords::max_size = LOG_MAX_SIZE,
		boost::log::keywords::time_based_rotation = boost::log::sinks::file::rotation_at_time_point(0, 0, 0),
		boost::log::keywords::format = COMMON_FMT,
		boost::log::keywords::auto_flush = true
	);

	boost::log::add_common_attributes();

	// Only output message with INFO or higher severity in Release.
	#ifndef _DEBUG
	boost::log::core::get()->set_filter(
		boost::log::trivial::severity >= boost::log::trivial::info
	);
	#endif
}