#include "Errors.hpp"
#include "Logger.hpp"
#include "../string/String.hpp"

namespace ostd
{
	RuntimeError& RuntimeError::create(u8 group, u64 code, u8 level, const String &msg)
	{
		m_errGroup = group;
		m_errCode = code;
		m_message = msg;
		m_errLevel = level;
		setTypeName("ostd::RuntimeError");
		validate();
		return *this;
	}

	void RuntimeError::fire(const String& extraMessage, OutputHandlerBase* outputHandler, BaseObject& userData, i32 _line_num, const String& _file_name)
	{
		if (isInvalid() || m_errGroup == 0x0 || m_errLevel == tErrorLevel::NoError || m_errCode == 0x0) return;
		String errorMessage = m_message + "\n";
		if (extraMessage != "")
			errorMessage += extraMessage + "\n";
		if (userData.isValid())
			errorMessage += "USER_DATA:\n" + userData.toString() + "\n";
		String msgEdit = "";
		msgEdit.add(String::getHexStr(m_errGroup)).add("//");
		msgEdit.add(String::getHexStr(m_errCode, true, 8)).add("  ::  ");
		if (_file_name != "")
		{
			msgEdit.add(_file_name).add(" ");
			if (_line_num > 0)
				msgEdit.add("[LINE: ").add(_line_num).add("]\n");
			else
				msgEdit.add("\n");
		}
		msgEdit.add(errorMessage);
		OutputHandlerBase* tmpOutHndl = nullptr;
		if (outputHandler != nullptr)
		{
			tmpOutHndl = &Logger::getOutputHandler();
			Logger::setOutputHandler(*outputHandler);
		}
		if (m_errLevel == tErrorLevel::Warning)
		{
			OX_WARN(msgEdit);
		}
		else if (m_errLevel == tErrorLevel::Error)
		{
			OX_ERROR(msgEdit);
		}
		else if (m_errLevel == tErrorLevel::Fatal)
		{
			OX_FATAL(msgEdit);
		}
		if (tmpOutHndl != nullptr)
			Logger::setOutputHandler(*tmpOutHndl);
	}
}
