#include "simplelog.h"

#include <iostream>
#include <iomanip>
#include <chrono>

// 头文件
#ifdef _WIN32
#include <io.h>
#include <tchar.h>
#include <direct.h>
#include <Windows.h>
#else
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif
#include <stdio.h>

#include <string>

// 获取当前进程的路径
std::string GetCurrentPath()
{
    char curr_path[1024];
#ifdef _WIN32
    ::GetModuleFileName(NULL, curr_path, MAX_PATH);
    (_tcsrchr(curr_path, '\\'))[1] = 0;
#else
    getcwd(curr_path, 1024);
    sprintf(curr_path, "%s/", curr_path);
#endif
    std::string str_curr_path = curr_path;
    return str_curr_path;
}

SimpleLog *SimpleLog::Instance()
{
	if (mInstance == nullptr)
	{
		std::lock_guard<std::mutex> guard(mMutex);
		if (mInstance == nullptr)
			mInstance = new SimpleLog;
	}
	return mInstance;
}

void SimpleLog::setSavePath(std::string path)
{
	mSavePath = path;
}

std::string SimpleLog::savePath()
{
	return mSavePath;
}

void SimpleLog::addLogTxt(std::string txt)
{
	auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
	
	std::stringstream ss;
	// ss << std::put_time(std::localtime(&t), "%Y-%m-%d-%H-%M-%S");
	std::string strTime;
	if (mSaveTimeSpan == Month)
	{
		ss << std::put_time(std::localtime(&t), "%Y-%m");
		strTime = ss.str();
	}
	else if (mSaveTimeSpan == Day)
	{
		ss << std::put_time(std::localtime(&t), "%Y-%m-%d");
		strTime = ss.str();
	}
	else if (mSaveTimeSpan == Hour)
	{
		ss << std::put_time(std::localtime(&t), "%Y-%m-%d-%H");
		strTime = ss.str();
	}
	else if (mSaveTimeSpan == Minute)
	{
		ss << std::put_time(std::localtime(&t), "%Y-%m-%d-%H-%M-%S");
		strTime = ss.str();
	}

	std::string logFileName = strTime + ".txt";
	logFileName = mSaveDir + "\\" + logFileName;
	out.open(logFileName, std::ios::out | std::ios::app);

	if (mShowTime)
	{
		using namespace std;
		using namespace std::literals;

		// 打印到标准输凿
		auto t = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
		// std::cout << std::put_time(std::localtime(&t), "%F %T") << std::endl;

		std::stringstream ss;
		ss << std::put_time(std::localtime(&t), "%F %T");
		std::string str = ss.str();

		out << str + " " + txt << std::endl;
	}
	else
	{
		out << txt << std::endl;
	}

	out.close();
}

void SimpleLog::setShowTime(bool show)
{
	mShowTime = show;
}

void SimpleLog::setSaveTimeSpan(SaveTimeSpan span)
{
	mSaveTimeSpan = span;
}

SimpleLog::SimpleLog()
{
	mSavePath = "";
	mShowTime = false;
	mSaveTimeSpan = Hour;
	mSaveDir = GetCurrentPath();
}

SimpleLog::~SimpleLog()
{
	out.close();
}

void SimpleLog::checkResource()
{
	// 检查配置文件目录是否存圿
}

SimpleLog *SimpleLog::mInstance = nullptr;
std::mutex SimpleLog::mMutex;
SimpleLog::GC SimpleLog::gc;

void addLogStr(std::string str)
{
	SimpleLog::Instance()->addLogTxt(str);
}
