// dui-demo.cpp : main source file
//

#include "stdafx.h"
#include "MainDlg.h"
#include "LoginDlg.h"
#include "SouiInit.h"
#include "CApp.h"
#include "CTool.h"
#include "Logger.h"
#include "SysProxy.h"
#include "log4z/log4z.h"

bool startWisth(const std::wstring& mainstr, const std::wstring& substr)
{
	return mainstr.find(substr) == 0 ? 1 : 0;
}

int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int /*nCmdShow*/)
{
	HRESULT hRes = OleInitialize(NULL);
	SASSERT(SUCCEEDED(hRes));
	 
	
	int nRet = 0;
	new Logger();
	new CApp();
	new CProcessManager();
	
	CApp::getSingletonPtr()->Init();
	CApp::getSingletonPtr()->SetMethod(hInstance);

	CApp::getSingletonPtr()->ChkeAndSetDtaPath();
	 
	
	if (!CApp::getSingletonPtr()->CheckOnlyOneInstance())
	{
		std::wstring pmPrefix = L"--pm=";
		std::wstring cmdLine(lpstrCmdLine);
		if (startWisth(cmdLine, pmPrefix))
			return CProcessManager::getSingletonPtr()->SubProcess(cmdLine.substr(pmPrefix.size()));
	}

	CreateDirectoryIgnoreExist(CApp::getSingletonPtr()->GetDataPath().c_str());

	CApp::getSingletonPtr()->CheckOnlyOneInstance();

	PortableModeUtil::SetAppId();
	/**/

	CProcessManager::getSingletonPtr()->SetInsTanCe(hInstance);



	//---------------------------防止程序多开-----------------------------------------
	auto hEventStatus = CreateEvent(nullptr, TRUE, FALSE, L"sproxy");
	if (hEventStatus)
	{
		if (GetLastError() == ERROR_ALREADY_EXISTS)
		{

			auto hwndMain = FindWindow(L"sproxy", NULL);//获取该窗体句柄
			if (hwndMain)
			{
				auto hwnpop = GetLastActivePopup(hwndMain);

				ShowWindow(hwnpop, SW_SHOW);
				SetForegroundWindow(hwnpop);
				//ShowWindow(hwndMain, SW_SHOW);

			}


			CloseHandle(hEventStatus);//互斥量存在释放句柄并复位互斥量

			//
			SStringT strDisplayInfo;
			strDisplayInfo.Format(L"sproxy 正在运行中.");
			MessageBox(GetForegroundWindow(), strDisplayInfo, L"", MB_ICONINFORMATION);
			return 0;
		}
	}//-----------------------------------------------------------------



	CSouiLoader Loader(hInstance);
	InitSystemRes(Loader.GetApp(), Loader.GetComMgr());
	InitUserRes(Loader.GetApp(), Loader.GetComMgr());
	new CTool();
	new SNotifyCenter();
	new CManageNetWork();

	TCHAR szCurrentDir[MAX_PATH] = { 0 };
	GetModuleFileName(NULL, szCurrentDir, sizeof(szCurrentDir));

	LPTSTR lpInsertPos = _tcsrchr(szCurrentDir, _T('\\'));
 
	_tcscpy(lpInsertPos + 1, _T("\0"));
 
	SetCurrentDirectory(szCurrentDir);
	Logger::getSingletonPtr()->Init(Logger::file_and_terminal, Logger::info);
	nRet = Run<CLoginDlg>(Loader.GetApp());

	if (CApp::getSingletonPtr()->GetOut() == 1)
	{
		nRet = Run<CMainDlg>(Loader.GetApp());
	}


	
	
	delete CTool::getSingletonPtr();
	delete SNotifyCenter::getSingletonPtr();
	
	
	
	delete CManageNetWork::getSingletonPtr();
	delete CApp::getSingletonPtr();
	delete Logger::getSingletonPtr();
	delete CProcessManager::getSingletonPtr();
	DisableSystemProxy();
	OleUninitialize();
	return nRet;
}
