#include <VoxelverseSession/VoxelverseClient/VoxelverseClient.hpp>
#include <VoxelverseSession/VoxelverseSession.hpp>

#define NOMINMAX
#include <stdlib.h>
#include <windows.h>
#include <shellapi.h>

void parseCommandLineArgs(int *argc, char ***argv)
{
    // Get the command line arguments as wchar_t strings
    wchar_t ** wargv = CommandLineToArgvW( GetCommandLineW(), argc );
    if (!wargv) { *argc = 0; *argv = NULL; return; }
    
    // Count the number of bytes necessary to store the UTF-8 versions of those strings
    int n = 0;
    for (int i = 0; i < *argc; i++)
        n += WideCharToMultiByte( CP_UTF8, 0, wargv[i], -1, NULL, 0, NULL, NULL ) + 1;
    
    // Allocate the argv[] array + all the UTF-8 strings
    *argv = (char**) malloc( (*argc + 1) * sizeof(char *) + n );
    if (!*argv) { *argc = 0; return; }
    
    // Convert all wargv[] --> argv[]
    char * arg = (char *)&((*argv)[*argc + 1]);
    for (int i = 0; i < *argc; i++)
    {
        (*argv)[i] = arg;
        arg += WideCharToMultiByte( CP_UTF8, 0, wargv[i], -1, arg, n, NULL, NULL ) + 1;
    }
    (*argv)[*argc] = NULL;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    int argc;
    char **argv;
    parseCommandLineArgs(&argc, &argv);

    voxelverse = std::make_unique<VoxelverseClient>();
    int status = voxelverse->start(argc, argv);

    free(argv);

    return status;
};