#include "stdafx.h"
#include "Global.h"
#include <SetupAPI.h>
#include <InitGuid.h>
#include <WinIoCtl.h>
#pragma comment(lib, "SetupAPI.lib")

namespace Global
{
	//////////////////////////////////////////////////////////////////////////
	// 全局变量;
	BOOL g_bTestHost = FALSE;
	TCHAR g_szCurModuleDir[MAX_PATH] = { 0 };
	TCHAR g_szCurModulePath[MAX_PATH] = { 0 };
	TCHAR g_szFna[MAX_PATH] = { 0 };
	TCHAR g_szConfig[MAX_PATH] = { 0 };
	std::string g_strMacs;
	std::vector<MacAddress> g_vtMac;

	// usb;
	static GUID UsbClassGuid = { 0xA5DCBF10L, 0x6530, 0x11D2, {0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED} };
	// mac;
	static GUID MacClassGuid = { 0xAD498944, 0x762F, 0x11D0, {0x8D, 0xCB, 0x00, 0xC0, 0x4F, 0xC3, 0x35, 0x8C} };
	// hdd;
	static GUID HDDClassGuid = { 0x53F56307, 0xB6BF, 0x11D0, {0x94, 0xF2, 0x00, 0xA0, 0xC9, 0x1E, 0xFB, 0x8B} };

	//////////////////////////////////////////////////////////////////////////
	// 全局函数;
	/************************************************************************/
	/*  函数：WriteTextLog[7/28/2009 Jeff];
			/*  描述：写文本日志;
			/*  参数：;
			/*  	[IN] ：;
			/*  返回：void;
			/*  注意：;
			/*  示例：;
			/*
			/*  修改：;
			/*  日期：;
			/*  内容：;
			/************************************************************************/
	void WriteTextLog(const TCHAR* format, ...)
	{
		// 将日志内容输入到文件中;
		// 获取今年年份;
		__time64_t gmt = time(NULL); // 获取当前日历时间(1900-01-01开始的Unix时间戳);
		struct tm gmtm = { 0 };
		localtime_s(&gmtm, &gmt); // 时间戳转成本地时间;

		// 解析出日志路径;
		TCHAR szlogpath[MAX_PATH] = { 0 };
		_stprintf_s(szlogpath, _T("%slog\\Serial Port%s Log %02d%02d.txt"), g_szCurModuleDir, g_szFna, gmtm.tm_mon + 1, gmtm.tm_mday);
		// 打开或创建文件;
		FILE* fp = NULL;
		//if (_taccess(szlogpath, 0) != -1)
#ifndef UNICODE
		if (_access(szlogpath, 0) != -1)
#else
		if (_taccess(szlogpath, 0) != -1)
#endif
		{ // 存在;
			if (0 == _tfopen_s(&fp, szlogpath, _T("a+")))
				// 移动到末尾;
				fseek(fp, 0, SEEK_END);
		}
		else
		{ // 不存在;
			_tfopen_s(&fp, szlogpath, _T("w+"));
		}

		if (fp == NULL)
			return;

		// 格式化前设置语言区域;
		TCHAR* old_locale = _tcsdup(_tsetlocale(LC_CTYPE, NULL));
		_tsetlocale(LC_CTYPE, _T("chs")); //设定中文;

		// 格式化日志内容;
		va_list args = NULL;
		int len = 0;
		TCHAR* buffer = NULL;
		va_start(args, format);
		// _vscprintf doesn't count. terminating '\0'
		len = _vsctprintf(format, args) + 1;
		buffer = (TCHAR*)malloc(len * sizeof(TCHAR));
		_vstprintf_s(buffer, len, format, args);
		_ftprintf(fp, _T("%04d-%02d-%02d %02d:%02d:%02d %s\n"), gmtm.tm_year + 1990, gmtm.tm_mon + 1, gmtm.tm_mday, gmtm.tm_hour, gmtm.tm_min, gmtm.tm_sec, buffer);

		// 关闭文件，释放资源并设置回原语言区域;
		free(buffer);
		fclose(fp);
		_tsetlocale(LC_CTYPE, old_locale);
		free(old_locale); //还原区域设定;
	}


	void replace_str(std::string& str, const std::string& before, const std::string& after)
	{
		for (std::string::size_type pos(0); pos != std::string::npos; pos += after.length())
		{
			pos = str.find(before, pos);
			if (pos != std::string::npos)
				str.replace(pos, before.length(), after);
			else
				break;
		}
	}

	// 去除空格;
	std::string& trim(std::string& str)
	{
		int nIndex = 0;
		while ((nIndex = str.find_first_of(' ')) != std::string::npos)
			str.erase(nIndex, 1);

		return str;
	}

	// hModule 模块句柄 NULL表示当前模块;
	bool GetVersion(IN const TCHAR* fname, OUT WORD* pdwFileVersion, OUT WORD* pdwProductVerion)
	{
		VS_FIXEDFILEINFO* pVi = NULL;
		DWORD dwHandle = 0;
		int size = GetFileVersionInfoSize(fname, &dwHandle);
		if (size > 0)
		{
			BYTE* buffer = new BYTE[size];
			memset(buffer, 0, size);

			if (GetFileVersionInfo(fname, 0, size, buffer))
			{
				if (VerQueryValue(buffer, _T("\\"), (LPVOID*)& pVi, (PUINT)& size))
				{
					pdwFileVersion[0] = HIWORD(pVi->dwFileVersionMS);
					pdwFileVersion[1] = LOWORD(pVi->dwFileVersionMS);
					pdwFileVersion[2] = HIWORD(pVi->dwFileVersionLS);
					pdwFileVersion[3] = LOWORD(pVi->dwFileVersionLS);

					pdwProductVerion[0] = HIWORD(pVi->dwProductVersionMS);
					pdwProductVerion[1] = LOWORD(pVi->dwProductVersionMS);
					pdwProductVerion[2] = HIWORD(pVi->dwProductVersionLS);
					pdwProductVerion[3] = LOWORD(pVi->dwProductVersionLS);

					delete[] buffer;
					return true;
				}
			}

			delete[] buffer;
		}

		return false;
	}

	BOOL GetVersion(IN HMODULE hModule, OUT DWORD(&dwFVArray)[4], OUT DWORD(&dwPVArray)[4])
	{
		TCHAR fname[MAX_PATH];
		VS_FIXEDFILEINFO* pVi;
		DWORD dwHandle;

		if (GetModuleFileName(hModule, fname, MAX_PATH))
		{
			INT nSize = GetFileVersionInfoSize(fname, &dwHandle);

			if (nSize > 0)
			{
				BYTE* pBuffer = new BYTE[nSize];
				memset(pBuffer, 0, nSize);

				if (GetFileVersionInfo(fname, 0, nSize, pBuffer))
				{
					if (VerQueryValue(pBuffer, _T("\\"), (LPVOID*)& pVi, (PUINT)& nSize))
					{
						dwFVArray[0] = HIWORD(pVi->dwFileVersionMS);
						dwFVArray[1] = LOWORD(pVi->dwFileVersionMS);
						dwFVArray[2] = HIWORD(pVi->dwFileVersionLS);
						dwFVArray[3] = LOWORD(pVi->dwFileVersionLS);

						dwPVArray[0] = HIWORD(pVi->dwProductVersionMS);
						dwPVArray[1] = LOWORD(pVi->dwProductVersionMS);
						dwPVArray[2] = HIWORD(pVi->dwProductVersionLS);
						dwPVArray[3] = LOWORD(pVi->dwProductVersionLS);

						delete[]pBuffer;
						return TRUE;
					}
				}

				if (pBuffer)
					delete[]pBuffer;
			}
		}

		return FALSE;
	}

	WCHAR* ASCII2UNICODE(IN LPCCH lpASCIIStr)
	{
		if (lpASCIIStr == NULL)
			return NULL;

		// 获取宽字符字节数;
		int cchWideChar = MultiByteToWideChar(CP_ACP, 0, lpASCIIStr, -1, NULL, 0);
		if (cchWideChar == 0)
			return NULL;

		// 转换成宽字符串;
		WCHAR* pWideChar = new WCHAR[cchWideChar + 1];
		memset(pWideChar, 0, sizeof(WCHAR) * (cchWideChar + 1));
		int nWriteNum = MultiByteToWideChar(CP_ACP, 0, lpASCIIStr, -1, pWideChar, cchWideChar);
		if (nWriteNum != cchWideChar)
		{
			if (pWideChar)
				delete[] pWideChar;
			return NULL;
		}

		return pWideChar;
	}

	BOOL UNICODE2UTF8(IN LPWCH lpUNICODEStr, OUT std::string& strResult)
	{
		if (lpUNICODEStr == NULL)
			return FALSE;

		// 获取多字节字符字节数;
		int cbMultiByte = WideCharToMultiByte(CP_UTF8, 0, lpUNICODEStr, -1, NULL, 0, NULL, NULL);
		if (cbMultiByte == 0)
			return FALSE;

		// 转换成多字节字符;
		CHAR* pResult = new CHAR[cbMultiByte];
		memset(pResult, 0, cbMultiByte);
		int nWriteNum = WideCharToMultiByte(CP_UTF8, 0, lpUNICODEStr, -1, pResult, cbMultiByte, NULL, NULL);
		if (nWriteNum != cbMultiByte)
			return FALSE;

		strResult = pResult;
		if (pResult)
			delete[] pResult;

		return TRUE;
	}

	BOOL ASCII2UTF8(IN LPCCH lpASCIIStr, OUT std::string& strResult)
	{
		// 将ASCII字符串转成UNICODE字符串;
		WCHAR* pWideChar = ASCII2UNICODE(lpASCIIStr);
		if (pWideChar == NULL)
			return FALSE;

		// 再将UICODE转成UTF8;
		BOOL bResult = UNICODE2UTF8(pWideChar, strResult);

		if (pWideChar)
			delete[] pWideChar;

		return bResult;
	}

	std::string EnCode_UTF8URL(IN const CHAR* pText)
	{
		std::string tt = "";
		std::string dd = "";
		ASCII2UTF8(pText, tt);

		size_t len = tt.length();
		for (size_t i = 0; i < len; i++)
		{
			if (isalnum((BYTE)tt.at(i)))
			{
				char tempbuff[2] = { 0 };
				sprintf_s(tempbuff, "%c", (BYTE)tt.at(i));
				dd.append(tempbuff);
			}
			else if (isspace((BYTE)tt.at(i)))
			{
				dd.append("+");
			}
			else
			{
				char tempbuff[4];
				sprintf_s(tempbuff, "%%%X%X", ((BYTE)tt.at(i)) >> 4, ((BYTE)tt.at(i)) % 16);
				dd.append(tempbuff);
			}
		}
		return dd;
	}

	void EnCode_UTF8URL(IN const CHAR* pText, OUT std::string& strResult)
	{
		std::string tt = "";
		ASCII2UTF8(pText, tt);

		size_t len = tt.length();
		for (size_t i = 0; i < len; i++)
		{
			if (isalnum((BYTE)tt.at(i)))
			{
				char tempbuff[2] = { 0 };
				sprintf_s(tempbuff, "%c", (BYTE)tt.at(i));
				strResult.append(tempbuff);
			}
			else if (isspace((BYTE)tt.at(i)))
			{
				strResult.append("+");
			}
			else
			{
				char tempbuff[4];
				sprintf_s(tempbuff, "%%%X%X", ((BYTE)tt.at(i)) >> 4, ((BYTE)tt.at(i)) % 16);
				strResult.append(tempbuff);
			}
		}
	}

	// 通过注册表查找系统当前串口信息;
	BOOL GetSysSerialPort(std::vector<std::string>& vtports)
	{
		HKEY hKey;
		LSTATUS lReg = 0;
		DWORD dwMaxValLen = 0;
		DWORD dwValNum = 0;
		lReg = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM", 0, KEY_QUERY_VALUE, &hKey);
		if (lReg != ERROR_SUCCESS)
		{
			return FALSE;
		}

		lReg = RegQueryInfoKeyA(hKey, NULL, NULL, NULL, NULL, NULL, NULL, &dwValNum, &dwMaxValLen, NULL, NULL, NULL);
		if (lReg != ERROR_SUCCESS)
		{
			return FALSE;
		}

		if (vtports.size())
		{
			vtports.clear();
		}

		LPSTR lpValName, lpComNum;
		DWORD dwValName, dwValSize = 6;
		for (DWORD i = 0; i < dwValNum; i++)
		{
			dwValName = dwMaxValLen + 1;
			dwValSize = 6;
			lpValName = (LPSTR)VirtualAlloc(NULL, dwValName, MEM_COMMIT, PAGE_READWRITE);
			lReg = RegEnumValueA(hKey, i, lpValName, &dwValName, NULL, NULL, NULL, NULL);
			if ((lReg != ERROR_SUCCESS) && (lReg != ERROR_NO_MORE_ITEMS))
			{
				continue;
			}
			lpComNum = (LPSTR)VirtualAlloc(NULL, 6, MEM_COMMIT, PAGE_READWRITE);
			lReg = RegQueryValueExA(hKey, lpValName, NULL, NULL, (LPBYTE)lpComNum, &dwValSize);
			if (lReg != ERROR_SUCCESS)
			{
				continue;
			}

			vtports.push_back(lpComNum);
			VirtualFree(lpValName, 0, MEM_RELEASE);
			VirtualFree(lpComNum, 0, MEM_RELEASE);
		}

		return TRUE;
	}

	INT GetMacAddress()
	{
		HDEVINFO hDevInfo;
		DWORD MemberIndex, RequiredSize;
		SP_DEVICE_INTERFACE_DATA DeviceInterfaceData;
		PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData;
		INT nTotal = 0;
		INT nNICKind = 0;

		// 获取设备信息集;
		hDevInfo = SetupDiGetClassDevs(&MacClassGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_INTERFACEDEVICE);
		if (hDevInfo == INVALID_HANDLE_VALUE)
		{
			return -1;
		}

		g_vtMac.clear();
		// 枚举设备信息集中所有设备;
		DeviceInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
		for (MemberIndex = 0; SetupDiEnumDeviceInterfaces(hDevInfo, NULL, &MacClassGuid, MemberIndex, &DeviceInterfaceData); MemberIndex++)
		{
			// 获取接收缓冲区大小，函数返回值为FALSE，GetLastError()=ERROR_INSUFFICIENT_BUFFER;
			SetupDiGetDeviceInterfaceDetail(hDevInfo, &DeviceInterfaceData, NULL, 0, &RequiredSize, NULL);

			// 申请接收缓冲区;
			DeviceInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(RequiredSize);
			if ( DeviceInterfaceDetailData == NULL)
				continue;
			DeviceInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

			// 获取设备细节信息;
			if (SetupDiGetDeviceInterfaceDetail(hDevInfo, &DeviceInterfaceData, DeviceInterfaceDetailData, RequiredSize, NULL, NULL))
			{
				HANDLE hDeviceFile;
				BOOL isOK = FALSE;
				if (_tcsnicmp(DeviceInterfaceDetailData->DevicePath + 4, TEXT("pci"), 3) != 0)
				{
					free(DeviceInterfaceDetailData);
					DeviceInterfaceDetailData = NULL;
					continue;
				}
				MacAddress tagMacAddress;
				tagMacAddress.nNICKind = NIC_PCI;
				_stprintf_s(tagMacAddress.szNICKind, _T("%s"), _T("NIC_PCI"));

				// 获取设备句柄;
				hDeviceFile = CreateFile(DeviceInterfaceDetailData->DevicePath,
					0,
					FILE_SHARE_READ | FILE_SHARE_WRITE,
					NULL,
					OPEN_EXISTING,
					0,
					NULL);

				if (hDeviceFile != INVALID_HANDLE_VALUE)
				{
					ULONG dwID;
					BYTE ucData[8];
					DWORD dwByteRet;

					// 获取原生MAC地址;
					dwID = OID_802_3_PERMANENT_ADDRESS;
					isOK = DeviceIoControl(hDeviceFile, IOCTL_NDIS_QUERY_GLOBAL_STATS, &dwID, sizeof(dwID), ucData, sizeof(ucData), &dwByteRet, NULL);
					if (isOK)
					{
						++nTotal;
						_stprintf_s(tagMacAddress.szDevicePath, _T("%s"), DeviceInterfaceDetailData->DevicePath);
						memset(tagMacAddress.szMacAddress, 0, sizeof(TCHAR) * MAX_PATH);
						// 将字节数组转换成16进制字符串;
						for (DWORD i = 0; i < dwByteRet; i++)
						{
							_stprintf_s(&tagMacAddress.szMacAddress[i * 3], MAX_PATH - (i * 3), (i != dwByteRet - 1) ? _T("%02X-") : _T("%02X"), ucData[i]);
						}

						g_vtMac.push_back(tagMacAddress);
					}
					CloseHandle(hDeviceFile);
				}
			}

			free(DeviceInterfaceDetailData);
			DeviceInterfaceDetailData = NULL;
		}

		SetupDiDestroyDeviceInfoList(hDevInfo);

#if 1
		g_strMacs.clear();
		std::vector<MacAddress>::iterator it = g_vtMac.begin();
		for (; it != g_vtMac.end(); it++)
		{
			g_strMacs.append(it->szMacAddress);
			g_strMacs.append("&");
		}
#endif

		return nTotal;
	}

	BOOL IsValidString(LPCTSTR lpszString)
	{
		if (lpszString == NULL)
			return FALSE;

		do
		{
			// ASCII可显示的字符;
			if (*lpszString < 32 || *lpszString > 126)
			{
				return FALSE;
			}
		} while (*++lpszString);

		return TRUE;
	}
} // namespace Global