#include <stdarg.h>
#include <time.h>
#include "Log.h"

#ifdef VIOPSF2_REMOVED
#include "AppConfig.h"
#include "PathUtils.h"
#else
#ifndef DISABLE_LOGGING
#include "PathUtils.h"
#endif
#endif

#include "StdStreamUtils.h"

#define LOG_PATH "logs"

#ifdef VIOPSF2_REMOVED
CLog::CLog()
{
#ifndef DISABLE_LOGGING
	m_logBasePath = CAppConfig::GetBasePath() / LOG_PATH;
	Framework::PathUtils::EnsurePathExists(m_logBasePath);
#endif
}

CLog::~CLog()
{

}

void CLog::Print(const char* logName, const char* format, ...)
{
#if defined(_DEBUG) && !defined(DISABLE_LOGGING)
	auto& logStream(GetLog(logName));
	va_list args;
	va_start(args, format);
	vfprintf(logStream, format, args);
	va_end(args);
	logStream.Flush();
#endif
}

Framework::CStdStream& CLog::GetLog(const char* logName)
{
	auto logIterator(m_logs.find(logName));
	if(logIterator == std::end(m_logs))
	{
		auto logPath = m_logBasePath / (std::string(logName) + ".log");
		auto logStream = Framework::CreateOutputStdStream(logPath.native());
		m_logs[logName] = std::move(logStream);
		logIterator = m_logs.find(logName);
	}
	return logIterator->second;
}
#else
#ifndef DISABLE_LOGGING
CLog::CLog()
{
	m_logBasePath = LOG_PATH;
	Framework::PathUtils::EnsurePathExists(m_logBasePath);
}

CLog::~CLog()
{

}

void CLog::Print(const char* logName, const char* format, ...)
{
	auto& logStream(GetLog(logName));
	va_list args;
	va_start(args, format);
	vfprintf(logStream, format, args);
	va_end(args);
	logStream.Flush();
}

Framework::CStdStream& CLog::GetLog(const char* logName)
{
	auto logIterator(m_logs.find(logName));
	if (logIterator == std::end(m_logs))
	{
		auto logPath = m_logBasePath / (std::string(logName) + ".log");
		auto logStream = Framework::CreateOutputStdStream(logPath.native());
		m_logs[logName] = std::move(logStream);
		logIterator = m_logs.find(logName);
	}
	return logIterator->second;
}
#else
CLog g_Log;

CLog::CLog()
{}

CLog::~CLog()
{}

CLog& CLog::GetInstance()
{
	return g_Log;
}

void CLog::Print(const char*, const char*, ...)
{}

#endif
#endif