#include"CivSysLog.h"
#include <time.h>

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

CivSysLog* CivSysLog::mInstance = nullptr;
CivSysLog::SafeClass CivSysLog::safeClass;

CivSysLog::CivSysLog()
{
	mLogName = "动态水力计算日志_"+ getCurrentTime2()+".log";
}

CivSysLog* CivSysLog::getInstance()
{
	if (mInstance == nullptr)
	{
		mInstance = new CivSysLog();
	}
	return mInstance;
}

void CivSysLog::setLog(const std::string& logName)
{ 
	mLogName = logName;
}

std::string CivSysLog::log()
{ 
	return mLogName;
}

std::string CivSysLog::getLogPath()
{
	std::string finalPath;

#ifdef _WIN32
	wchar_t exeFullPath[MAX_PATH]; // Full path   
    std::string strPath = "";
    GetModuleFileName(NULL, exeFullPath, MAX_PATH);
    char CharString[MAX_PATH];
    size_t convertedChars = 0;
    wcstombs_s(&convertedChars, CharString, MAX_PATH, exeFullPath, _TRUNCATE);
	strPath = (std::string)CharString;    // Get full path of the file   
    int pos = strPath.find_last_of('\\', strPath.length());
	finalPath = strPath.substr(0, pos);  // Return the directory without the file name   
#else
	char buf1[256];
	_getcwd(buf1, sizeof(buf1));
	finalPath = buf1;
#endif // _WIN32

	return finalPath;
}

// 错误记录
void CivSysLog::error(std::string text, std::string handler, std::string method)
{
	writeMesssage(text, handler, method, std::string("error"));
}

// 调试信息记录
void CivSysLog::debug(std::string text, std::string handler, std::string method)
{
	writeMesssage(text, handler, method, std::string("debug"));
}

// 一般信息记录
void CivSysLog::info(std::string text, std::string handler, std::string method)
{
	writeMesssage(text, handler, method,"Info");
}

// 警告记录
void CivSysLog::warning(std::string text, std::string handler, std::string method)
{
	writeMesssage(text,handler,method,"Warning");
}

void CivSysLog::writeMesssage(std::string text, std::string handler, std::string method, std::string loglevel)
{
	mOutfile.open(mLogName.c_str(), std::ios::app);
	if(mOutfile)
	{
		mOutfile << "[" << getCurrentTime() << "]" << "[" << loglevel << "] " << method << " " << text << std::endl;
		mOutfile.close();
	}
}

// 获取当前时间
std::string CivSysLog::getCurrentTime()
{
	time_t rawtime;
	struct tm* timeinfo;
	char s[100];
	time(&rawtime);

	timeinfo = localtime(&rawtime);
	time_t tick = mktime(timeinfo);
	strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", timeinfo);

	return s;
}

// 获取当前时间
std::string CivSysLog::getCurrentTime2()
{
	time_t rawtime;
	struct tm* timeinfo;
	char s[100];
	time(&rawtime);

	timeinfo = localtime(&rawtime);
	time_t tick = mktime(timeinfo);
	strftime(s, sizeof(s), "%Y%m%d", timeinfo);

	return s;
}
