#include "thardware.h"

#include <Windows.h>
#include <cstdio>

#include <Iphlpapi.h>
#include <NtDDNdis.h>
#include <string>

#pragma comment(lib, "Iphlpapi.lib")

namespace TC {

THardWare::THardWare() {}

static bool GetPhyMacAddress(const char *strServiceName, char *RealMAC)
{
    bool bRet = false;
    // char pstrBuf[512] = {0};
    // sprintf(pstrBuf, "//./%s", strServiceName);

    // HANDLE hDev = CreateFileA(pstrBuf,
    //                           GENERIC_READ | GENERIC_WRITE,
    //                           FILE_SHARE_READ | FILE_SHARE_WRITE,
    //                           NULL,
    //                           OPEN_EXISTING,
    //                           0,
    //                           0);
    // if (hDev != INVALID_HANDLE_VALUE) {
    //     int inBuf;
    //     BYTE outBuf[256] = {0};
    //     DWORD BytesReturned;
    //     inBuf = OID_802_3_PERMANENT_ADDRESS;

    //     if (DeviceIoControl(hDev,
    //                         IOCTL_NDIS_QUERY_GLOBAL_STATS,
    //                         (LPVOID) &inBuf,
    //                         4,
    //                         outBuf,
    //                         256,
    //                         &BytesReturned,
    //                         NULL)) {
    //         char buff[256] = {0};
    //         sprintf(buff,
    //                 "%d%d%d%d%d%d",
    //                 outBuf[0],
    //                 outBuf[1],
    //                 outBuf[2],
    //                 outBuf[3],
    //                 outBuf[4],
    //                 outBuf[5]);
    //         bRet = true;
    //         memcpy(RealMAC, buff, strlen(buff));
    //     }
    //     CloseHandle(hDev);
    // }
    return bRet;
}
std::string THardWare::machineCode()
{
    char Macstr[256] = {0};
    ULONG uSize = 0;
    DWORD dwResult = GetAdaptersInfo(NULL, &uSize);
    if (dwResult == ERROR_BUFFER_OVERFLOW) {
        PIP_ADAPTER_INFO piai1 = (PIP_ADAPTER_INFO) new BYTE[uSize];
        PIP_ADAPTER_INFO piai = piai1;
        dwResult = GetAdaptersInfo(piai, &uSize);
        if (ERROR_SUCCESS == dwResult) {
            const char *card1 = "QF9700";
            const char *card2 = "RD9700";
            while (piai) //获取多个网卡MAC地址
            {
                //QF9700 RD9700 特殊USB网卡处理
                if (strncmp(piai->Description, card1, strlen(card1)) == 0
                    || strncmp(piai->Description, card2, strlen(card2)) == 0) {
                    piai = piai->Next;
                    continue;
                }
                char mac[32] = {0};
                GetPhyMacAddress(piai->AdapterName, mac);
                piai = piai->Next;
                ::sprintf(Macstr, "%s%s", Macstr, mac); //把多个网卡MAC地址拼接
            }
        }
        delete[] piai1;
    }
    return std::string(Macstr);
}

} // namespace TC
