// NetTunnelSDKTestApp.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "globalcfg.h"

#include <strsafe.h>

#include "common.h"
#include "tunnel.h"
#include "user.h"
#include "usrerr.h"

const TCHAR *g_AppPath = TEXT("C:\\Users\\HuangXin\\Documents\\development\\visual_studio\\tunnel_windows\\x64\\Debug");
const TCHAR *g_SvrUserName = TEXT("tunnel_svr");
const TCHAR *g_PlatformURL = TEXT("http://xajhuang.com:9276");

//const TCHAR *g_PlatformURL = TEXT("http://localhost:9276");

void test_socket() {
    /*WSADATA wsa_data;
    WORD wsa_version = MAKEWORD(2, 2);
    WSAStartup(wsa_version, &wsa_data);*/
    const SOCKET   sd = socket(AF_INET, SOCK_STREAM, 0);    //server descriptor
    sockaddr_in server {};
    int addrSize = sizeof(sockaddr_in);

    server.sin_family      = AF_INET;
    server.sin_addr.s_addr = inet_addr (TEXT("127.0.0.1"));
    server.sin_port        = htons(0);

    if (bind(sd, reinterpret_cast<struct sockaddr *>(&server), sizeof(struct sockaddr)) == -1) {
        printf("error....\n");
    }

    printf("Set Bind Port: %d\n", ntohs(server.sin_port));    //is still 0

    sockaddr_in bindAddr {};

    int ret = getsockname(sd, reinterpret_cast<struct sockaddr *>(&bindAddr), &addrSize);

    printf("Bind port %d ret: %d\n", ntohs(bindAddr.sin_port), WSAGetLastError());
}

#if 0
int service_test() {
    TCHAR     szSvcName[]  = TEXT("WireGuard");
    SC_HANDLE schSCManager = nullptr;
    SC_HANDLE schService   = nullptr;

    SERVICE_STATUS_PROCESS ssStatus;
    DWORD                  dwOldCheckPoint  = 0;
    DWORD                  dwStartTickCount = 0;
    DWORD                  dwWaitTime       = 0;
    DWORD                  dwBytesNeeded    = 0;

    // Get a handle to the SCM database.
    schSCManager = OpenSCManager(nullptr,                   // local computer
                                 nullptr,                   // ServicesActive database
                                 SC_MANAGER_ALL_ACCESS);    // full access rights

    if (nullptr == schSCManager) {
        printf("OpenSCManager failed (%d)\n", GetLastError());
    }

    // Get a handle to the service.

    schService = OpenService(schSCManager,                                            // SCM database
                             szSvcName,                                               // name of service
                             SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS);    // full access

    if (schService == nullptr) {
        printf("OpenService failed (%d)\n", GetLastError());
        CloseServiceHandle(schSCManager);
    }

    // Check the status in case the service is not stopped.

    if (!QueryServiceStatusEx(schService,                        // handle to service
                              SC_STATUS_PROCESS_INFO,            // information level
                              (LPBYTE)&ssStatus,                 // address of structure
                              sizeof(SERVICE_STATUS_PROCESS),    // size of structure
                              &dwBytesNeeded))                   // size needed if buffer is too small
    {
        printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
        CloseServiceHandle(schService);
        CloseServiceHandle(schSCManager);
    } else {
        // Check if the service is already running. It would be possible
        // to stop the service here, but for simplicity this example just returns.
        printf("Service status: ");
        switch (ssStatus.dwCurrentState) {
            case SERVICE_STOPPED:
            case SERVICE_STOP_PENDING:
                printf("Stop");
                break;
            case SERVICE_PAUSED:
            case SERVICE_PAUSE_PENDING:
                printf("Pause");
                break;
            case SERVICE_CONTINUE_PENDING:
            case SERVICE_RUNNING:
            case SERVICE_START_PENDING:
                printf("Running");
                break;
        }
        cout << endl;
    }

    cin.get();
    return 0;
}

bool test_code() {
    char temp_path[MAX_PATH + 1] = { 0 };
    if (!::GetTempPathA(MAX_PATH, temp_path))
    {
        //LOG_ERROR("GetTempPathA failed! we use the default logger!");
        strcpy_s(temp_path, MAX_PATH, "c:\\windows\\temp\\");
    }

    char log_file[MAX_PATH + 1] = { 0 };
    sprintf_s(log_file, MAX_PATH, "%s%s", temp_path, "tunnel.log");

#ifdef _DEBUG
    LOG_LEVEL log_level = LOG_DEBUG;
#else
    LOG_LEVEL log_level = TUNNEL_LOG_INFO;
#endif

    int ret = TunnelSDKInitEnv(NULL, g_PlatformURL, log_file, log_level, true);
    if (ret != ERR_SUCCESS)
    {
        //LOG_ERROR("TunnelSDKInitEnv failed! err=%d!", ret);
        return false;
    }

    std::string local_ip = "127.0.0.1";
    PUSER_SERVER_CONFIG server_config = NULL;
    ret = GetUserServerConfigure(NULL, local_ip.c_str(), &server_config);
    if (ret != ERR_SUCCESS)
    {
        //LOG_ERROR("GetUserServerConfigure failed! err=%d!", ret);
        return false;
    }
}
#endif

int tunnel_service() {
    PUSER_SERVER_CONFIG pSvrCfg;
    //TCHAR               logPath[MAX_PATH];

    TunnelSDKInitEnv(nullptr, g_PlatformURL, nullptr, LOG_DEBUG, true);

    //StringCbPrintf(logPath, MAX_PATH, TEXT("%s\\TestApp.log"), g_AppPath);
    //InitTunnelSDKLog(nullptr, LOG_DEBUG);

    // Server 端用户名建议固定为一个字符串，因为每个云电脑上有且只有一个用户名, 长度不要超过32字符
    int ret = GetUserServerConfigure(g_SvrUserName, "asfdafdafdaf", &pSvrCfg);
    if (ERR_SUCCESS != ret) {
        SPDLOG_ERROR(TEXT("GetUserServerConfigure Error: {0}"), ret);
        return 0;
    }

    CreateControlService(pSvrCfg);
    return 0;
}

int main() {
    bool bRet;
    IsWireGuardServerRunning(TEXT("tunnel_svr"), &bRet);
    SPDLOG_INFO(TEXT("IsWireGuardServerRunning tunnel_svr: {0}"), bRet);
    //ShowRouteTable();
    //NetShare();
    //GetInterface();
    //CryptoExample();
    //SetRouteTable();

    //CreatePorxyService();
    //test_code();
    //test_socket();
    tunnel_service();
    //net_nat();

    //main_wireguard(true);
    //main_wireguard_getinfo();

    while (true) {
        Sleep(100);
    }
    return 0;
}

// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单

// 入门使用技巧:
//   1. 使用解决方案资源管理器窗口添加/管理文件
//   2. 使用团队资源管理器窗口连接到源代码管理
//   3. 使用输出窗口查看生成输出和其他消息
//   4. 使用错误列表窗口查看错误
//   5. 转到“项目”>“添加新项”以创建新的代码文件，或转到“项目”>“添加现有项”以将现有代码文件添加到项目
//   6. 将来，若要再次打开此项目，请转到“文件”>“打开”>“项目”并选择 .sln 文件