// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "stdafx.h"
#include "PipeClient.h"
#include "Utility.h"
#include "OGCAssist.h"

DWORD WINAPI WorkThreadProc(LPVOID lParam)
{
	// 注入成功后,启动管道进行通信;
	if ( Utility::g_pPipeClient == NULL )
	{
		Utility::g_pPipeClient = new CPipeClient(Utility::g_cfgCtx.szPipeName);
		Utility::g_pPipeClient->StartWork();
	}

	Assist::InitCallData();
	BOOL bInject = Assist::HijackedAllCall();

	//::MessageBox(NULL, _T("劫持成功"), _T(""), MB_OK);
	Utility::dprintf(_T("劫持成功\n"));

	WaitForSingleObject(Utility::hWorkThreadProc,INFINITE);

	// 恢复劫持数据;
	Assist::RestoreAllCall();

	// 主线程结束,DLL自我卸载;
	Utility::FreeLibraryAndExit();

	return 0;
}

#ifdef _CONSOLE
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;
	Utility::dprintf(_T("注入\n"));
	Utility::GetConfigContent();
	if ( Utility::g_pPipeClient == NULL )
	{
		Utility::g_pPipeClient = new CPipeClient(Utility::g_cfgCtx.szPipeName);
		Utility::g_pPipeClient->StartWork();
	}
	
	int i = 0;
	TCHAR szData[MAX_PATH] = {0};
	while (true)
	{
#if 0
		_stprintf(szData, _T("发送内容00000000000000000000000000000000000000000：%d, %d"), ::GetCurrentProcessId(), i++);
		Utility::g_pPipeClient->SendData((LPBYTE)szData, _tcslen(szData));
#else
		MSG_INFO msg_info;
		msg_info.dwClientId = GetCurrentProcessId();
		_stprintf(msg_info.szClientName, _T("%s"), _T("OGCAssist"));
		msg_info.byResult = TRUE;
		_stprintf((char*)msg_info.byData, _T("%s"), _T("OGCAssist dfdfdfdfdfdfdfdfdf"));

		PACKAGE pak;
		pak.header.byMsgType = C2S_DISCONNECT;
		pak.header.dwPackageLen = sizeof(DATAHEADER) + sizeof(MSG_INFO);
		pak.buf = &msg_info;

		Utility::g_pPipeClient->SendPackage(pak);
#endif
		Sleep(500);
	}

	system("pause");
}
#else
BOOL APIENTRY DllMain( HMODULE hModule,DWORD  ul_reason_for_call,LPVOID lpReserved)
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		{
			Utility::dprintf(_T("注入\n"));
			Utility::g_hDLLModule = hModule;
			Utility::GetConfigContent();
			Utility::g_WndInfo.dwProcessId = GetCurrentProcessId();
			Utility::hWorkThreadProc = CreateThread(NULL, 0, WorkThreadProc, NULL, 0, NULL);
		}
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}

#endif