#include "LogMgr.h"
#include <iostream>
#include <fstream>
#include "../Common.h"

//#pragma comment(lib, "Common.lib")
XLogMgr* XLogMgr::m_instance = nullptr;

XLogMgr::XLogMgr()
{
	XInit();
}

XLogMgr::~XLogMgr()
{
	if (m_logger)
	{
		m_logger->flush();
	}
}

void XLogMgr::FlushLog()
{
	if (m_logger)
	{
		m_logger->flush();
	}

}
void XLogMgr::XInit()
{
#ifdef _X_OPEN_LOG_
	spd::set_level(spd::level::trace);
	spd::set_pattern("[%Y-%m-%d %H:%M:%S.%e][thread %t][%l] %v");
	m_FileName = "quantApi.log";
	//string sFilePath = CCommon::GetExePath() +"\\"+ m_FileName;
	string sFilePath = CCommon::GetExePath() + "\\" + m_FileName;
	ofstream file;
	file.open(sFilePath, ios::out | ios::app | ios::binary);
	if (!file) return;
	file.close();
	//m_logger = spd::basic_logger_mt("LogMgr", sFilePath); //
	m_logger = spd::rotating_logger_mt("LogMgr", sFilePath,50000000,5);
	//m_logger = spd::daily_logger_mt("daily_logger",sFilePath, 2, 30);
	m_logger->flush_on(spd::level::trace);
#endif
}

std::string XLogMgr::SC_Trace(vector<string> vParam)
{
	if (vParam.size() < 1)return"0";
	return Log(vParam[0], spd::level::trace);
}

std::string XLogMgr::SC_Debug(vector<string> vParam)
{
	if (vParam.size() < 1)return"0";
	return Log(vParam[0], spd::level::debug);
}

std::string XLogMgr::SC_Info(vector<string> vParam)
{
	if (vParam.size() < 1)return"0";
	return Log(vParam[0], spd::level::info);
}

std::string XLogMgr::SC_Warn(vector<string> vParam)
{
	if (vParam.size() < 1)return"0";
	return Log(vParam[0], spd::level::warn);
}

std::string XLogMgr::SC_Err(vector<string> vParam)
{
	if (vParam.size() < 1)return"0";
	return Log(vParam[0], spd::level::err);
}

std::string XLogMgr::Log(const string sInfo, int nLevel /*= spd::level::trace*/, char* sFunc)
{
	if (m_logger == nullptr) return "0";

	if (sFunc)
	{
		string strFunc(sFunc);
		strFunc = strFunc + " " + sInfo;
		if (nLevel == spd::level::trace) m_logger->trace(strFunc);
		else if (nLevel == spd::level::debug) m_logger->debug(strFunc);
		else if (nLevel == spd::level::info) m_logger->info(strFunc);
		else if (nLevel == spd::level::warn) m_logger->warn(strFunc);
		else if (nLevel == spd::level::err) m_logger->error(strFunc);
	}
	else
	{
		if (nLevel == spd::level::trace) m_logger->trace(sInfo);
		else if (nLevel == spd::level::debug) m_logger->debug(sInfo);
		else if (nLevel == spd::level::info) m_logger->info(sInfo);
		else if (nLevel == spd::level::warn) m_logger->warn(sInfo);
		else if (nLevel == spd::level::err) m_logger->error(sInfo);
	}
	
	return "1";
}

std::string XLogMgr::Log(const char* sInfo, int nLevel /*= spd::level::trace*/, char* sFunc)
{
	string strFunc(sFunc);
	string str = strFunc + " " + sInfo;
	return Log(str, nLevel);
}

