// LogModule.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"
#include "LogModule.h"
#include <Shlwapi.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 唯一的应用程序对象

CWinApp theApp;

using namespace std;

CIOCPModel g_IOCP; // 主要对象，完成端口模型

// 启动tcp服务;
BOOL StartServer(unsigned int port)
{
	// 1.加载配置文件;
	TCHAR szDrive[_MAX_DRIVE] = { 0 };
	TCHAR szDir[_MAX_DIR] = { 0 };
	TCHAR szExt[_MAX_DIR] = { 0 };
	::GetModuleFileName(NULL, Global::g_szCurModulePath, sizeof(Global::g_szCurModulePath) / sizeof(TCHAR));
	_tsplitpath_s(Global::g_szCurModulePath, szDrive, szDir, Global::g_szFna, szExt);
	_tcscpy_s(Global::g_szCurModuleDir, szDrive);
	_tcscat_s(Global::g_szCurModuleDir, szDir);

	// 初始化网络库;
	if ( !g_IOCP.LoadSocketLib() )
	{
		return FALSE;
	}

	Global::WriteTextLog(_T("初始化网络库成功"));

	// 开启tcp服务;
	if ( !g_IOCP.Start(port) )
	{
		return FALSE;
	}

	Global::g_time = time(NULL);
	Global::g_lastTime = COleDateTime::GetCurrentTime();

	Global::WriteTextLog(_T("开启TCP服务成功"));
	if ( PathFileExists(Global::g_szConfig) )
	{
		// runner_tcp_port
		TCHAR szTcpPort[10] = {0};
		_itoa_s(port, szTcpPort, 10);
		Global::WriteTextLog(_T("配置文件路径：%s"), Global::g_szConfig);
		for ( int i = 0; i < 10; i++ )
		{
			if (!WritePrivateProfileString(_T("COMM"), _T("runner_tcp_port"), szTcpPort, Global::g_szConfig))
				Global::WriteTextLog(_T("保存端口号：%d 失败; 原因：%d"), port, GetLastError());
			else
			{
				Global::WriteTextLog(_T("保存端口号：%d 成功;"), port);
				break;
			}
		}
	}

	return TRUE;
}

// 停止tcp服务;
void StopServer()
{
	g_IOCP.Stop();
}

// 是否写入日志文件;
void EnableWriteLog(bool bEnable)
{
	Global::g_bEnableLog = bEnable;
	if ( !bEnable )
		Global::ClosePythonLog();
	Global::WriteTextLog(_T("当前日志路径：%s; 状态：%s"), Global::g_szLogPath, bEnable ? _T("启用日志") : _T("禁用日志") );
}

void SetCaselogPath(LPCTSTR lpCaselogPath)
{
	if ( lpCaselogPath == NULL || lpCaselogPath[0] == '\0')
		return;

	Global::WriteTextLog(_T("设置日志路径：%s"), lpCaselogPath);
	_stprintf_s(Global::g_szLogPath, _T("%s"), lpCaselogPath);
	Global::WritePythonLog(_T("C++ Operation"));
}

void SetConfigPath(LPCTSTR lpConfigPath)
{
	if ( lpConfigPath == NULL || lpConfigPath[0] == '\0')
		return;

	_stprintf_s(Global::g_szConfig, _T("%s"), lpConfigPath);
}

void SetCaselogPath3(const char* buffer, const int& len)
{
	if ( buffer == NULL || buffer[0] == '\0')
		return;

	Global::WriteTextLog(_T("路径3：%s, len=%d"), (char*)buffer, len);
	_tcscpy_s(Global::g_szLogPath, (char*)buffer);
}

LPCTSTR GetCaselogPath()
{
	return Global::g_szLogPath;
}

__int64 GetReceivePrintTime()
{
	return Global::g_time;
}

void SetReceivePrintTime(__int64 dt)
{
	Global::g_time = dt;
}

void ClosePythonLog()
{
	Global::ClosePythonLog();
}