#include "StdAfx.h"
#include "Utility.h"
#include <time.h>

#define MAX_SIZE 8192

namespace Utility
{
    // 当前DLL模块句柄;
    HMODULE g_hDLLModule = NULL;
    // 当前DLL内部工作者线程句柄;
    HANDLE hWorkThreadProc = NULL;
    // 当前DLL所在路径;
    TCHAR g_szCurModulePath[MAX_PATH] = {0};
    // 管道实例;
    CPipeClient *g_pPipeClient = NULL;

    // 配置文件名称;
    TCHAR g_szConfigFile[MAX_PATH] = {0};
    // 配置文件内容;
    CFG_CTX g_cfgCtx;
    // DLL所在进程窗口信息;
    WndInfo g_WndInfo;

    //////////////////////////////////////////////////////////////////////////
    // 全局函数;
    // 获取配置文件内容;
    void GetConfigContent()
    {
        // 获取dll的目录;
        TCHAR szDrive[MAX_PATH] = { 0 };
        TCHAR szDir[MAX_PATH] = { 0 };
        TCHAR szExt[MAX_PATH] = { 0 };
        TCHAR szFna[MAX_PATH] = { 0 };
        ::GetModuleFileName(g_hDLLModule, g_szCurModulePath, sizeof(g_szCurModulePath) / sizeof(TCHAR));
        _tsplitpath_s(g_szCurModulePath, szDrive, szDir, szFna, szExt);
        _tcscpy_s(g_szCurModulePath, szDrive);
        _tcscat_s(g_szCurModulePath, szDir);
        // 设置配置文件;
        _stprintf_s(g_szConfigFile, _T("%s%s"), g_szCurModulePath, _T("Assist.ini"));

        // 读取配置文件;
        TCHAR szValue[MAX_PATH] = {0};
        GetPrivateProfileString(_T("Windows"), _T("Title"), _T(""), g_cfgCtx.szWindowTitel, MAX_PATH, g_szConfigFile);
        GetPrivateProfileString(_T("Pipe"), _T("Name"), _T("Assist"), szValue, MAX_PATH, g_szConfigFile);
        _stprintf_s(g_cfgCtx.szPipeName, _T("\\\\.\\pipe\\%s"), szValue);
        GetPrivateProfileString(_T("Process"), _T("Name"), _T("Game.exe"), g_cfgCtx.szWndProcessName, MAX_PATH, g_szConfigFile);
    }

    void FreeLibraryAndExit()
    {
        if ( g_pPipeClient )
            delete g_pPipeClient;
        g_pPipeClient = NULL;

        if ( g_hDLLModule )
            FreeLibraryAndExitThread(g_hDLLModule, 0);
    }

    void dprintf(TCHAR* pszStr, ...)
    {
        TCHAR szData[MAX_SIZE] = {0};
        // 获取今年年份;
        __time64_t gmt = time(NULL);// 获取当前日历时间(1900-01-01开始的Unix时间戳);
        struct tm gmtm = { 0 };
        localtime_s(&gmtm, &gmt); // 时间戳转成本地时间;
#if _MSC_VER >= 1200 && _MSC_VER < 1500
        sprintf(szData, _T("[Assist] %04d-%02d-%02d %02d:%02d:%02d "), gmtm.tm_year + 1900, gmtm.tm_mon + 1, gmtm.tm_mday, gmtm.tm_hour, gmtm.tm_min, gmtm.tm_sec);
#else
        _stprintf_s(szData, _T("[Assist] %04d-%02d-%02d %02d:%02d:%02d "), gmtm.tm_year + 1900, gmtm.tm_mon + 1, gmtm.tm_mday, gmtm.tm_hour, gmtm.tm_min, gmtm.tm_sec);
#endif
        int len = _tcslen(szData)*sizeof(TCHAR);
        va_list args;
        va_start(args, pszStr);
        _vsntprintf_s(szData + len, MAX_SIZE - len, MAX_SIZE - len, pszStr, args);
        va_end(args);
        _tcscat_s(szData, "\n");
        OutputDebugString(szData);
    }
};
