#include "Logger.h"

#include <windows.h>
#include <mutex>
#include "Utils.h"
//#include "common/spdlogger.h"

std::mutex g_mutex;

Logger::Logger(Logger::ELogType logtype, std::string filename, int edit) : line_(edit)
{
	auto index = filename.find_last_of('\\');
	if (index != std::string::npos)
	{
		filename_ = filename.substr(index + 1);
	}
	else
	{
		filename_ = filename;
	}
	log_type_ = logtype;
}

Logger::~Logger()
{
	if (log_type_ == ELogType::E_LOG_OFF)
	{
		return;
	}
	static std::string strLogType[int(ELogType::E_LOG_OFF)] = { "DEBUG", "INFO", "WARN", "ERROR" };


	// std::lock_guard<std::mutex> lock(g_mutex);  // 虚构时自动解锁
	g_mutex.lock();
	//BACKGROUND代表背景，FOREGROUND代表前景
	//SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);//设置黄色（红色+绿色）
	//SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);

	std::string text = oss_.str();

	if (log_type_ == ELogType::E_LOG_DEBUG)
	{
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN);
		//Spdlogger::debug(text.c_str());
	}
	else if (log_type_ == ELogType::E_LOG_INFO)
	{
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_BLUE | FOREGROUND_GREEN);
		//Spdlogger::info(text.c_str());
	}
	else if (log_type_ == ELogType::E_LOG_WARN)
	{
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN);
		//Spdlogger::warn(text.c_str());
	}
	else if (log_type_ == ELogType::E_LOG_ERROR)
	{
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED);
		//Spdlogger::error(text.c_str());
	}
	else
	{
		SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
	}

	//std::cout << "[" << filename_ << ":" << line_ << "] [" << Utils::time_now_string_ms() << "][" << strLogType[int(log_type_)] << "] ";
	std::cout << "[" << Utils::timeStrMS() << "][" << strLogType[int(log_type_)] << "] ";
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
	std::cout << "- " << text << std::endl << std::flush;
	g_mutex.unlock();
}
