#include "ErrorHandler.hpp"
#include <Logger.hpp>
#include <system_time.hpp>
#include <iostream>
#include <StateVariables.hpp>

void ErrorHandler::cpfAssert(bool forceRecovery, std::string_view comment)
{
	std::cout << "cpfAssert fired, comment:" << comment << std::endl;
	// Logger::logEngLine()
	if(forceRecovery)
	{
		StateVariables::setForceRecovery();
	}
}
bool ErrorHandler::logError()
{
	uint64_t elapsedSec = 0;
	uint64_t ticksNow = 0;
	bool returnValue = false;
	std::string comment{};

	ticksNow = systime::getUptimeMilliseconds();

	if(firstError) // Check if first error
	{
		numErrors = 1;
		lastTickCount = ticksNow;
		firstError = false;
		comment = id + ": first error";
		returnValue = false;
	}
	else // Check if time out has elapsed
	{
		elapsedSec = (ticksNow - lastTickCount) / 1000;
		if(elapsedSec > timeoutSec)
		{
			numErrors = 1;
			lastTickCount = ticksNow;
			comment = id + ": error handler timeout, numErrors = 1";
			returnValue = false;
		}
		else // Check if errors meets threshold for criticallity
		{
			numErrors++;
			if(numErrors >= critThresh) // reached criticallity
			{
				lastTickCount = ticksNow;
				comment = id + ": critical error threshold reached, numErrors = " +
						  std::to_string(numErrors);
				numErrors = 0;
				returnValue = true;
			}
			else // hasn't reached criticallity
			{
				lastTickCount = ticksNow;
				comment = id + ": numErrors = " + std::to_string(numErrors);
				returnValue = false;
			}
		}
	}

	Logger::logLine(ALWAYS, comment);
	return returnValue;
}

void ErrorHandler::criticalErrorHandler()
{
	std::string comment = id + "Reached critical error handler";
	Logger::logLine(ALWAYS, comment);
}
