#ifndef UNICODE
#define UNICODE
#endif 

#include "MainApplication.h"
#include "GuiApplication.h"
#include "CommandLineArgs.h"
#include "Win32WindowInterface.h"
#include "FileLogger.h"
#include "StringUtils.h"

#include "windows.h"

#include <iostream>
#include <vector>
#include <string>

void initializeCommandLineArgs(CommandLineArgs* args)
{
    int nArgs{ 0 };
    auto szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
    if (szArglist == nullptr)
    {
        return;
    }

    std::vector<std::string> windowsArgs(nArgs);
    for (int idx = 0; idx < nArgs; idx++)
    {
        windowsArgs[idx] = StringUtils::convert(szArglist[idx]);
    }
    LocalFree(szArglist);

    args->Process(windowsArgs);
}

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
    std::ofstream out("out.txt");
    std::cout.rdbuf(out.rdbuf());

    auto args = CommandLineArgs::CreateUnique();
    initializeCommandLineArgs(args.get());
    args->RecordLaunchPath();

    // Start the main app
    auto main_app = MainApplication::Create();

    auto applicationContext = std::make_unique<Win32ApplicationContext>();
    applicationContext->hInstance = reinterpret_cast<void*>(hInstance);
    applicationContext->nCmdShow = nCmdShow;

    main_app->Initialize(std::move(args), std::move(applicationContext));

    MLOG_INFO("Creating GUI Application");

    // Start the gui application
    auto gui_app = GuiApplication();
    gui_app.SetMainApplication(main_app);

    MLOG_INFO("Running GUI Application");
    gui_app.Run();

    main_app->ShutDown();
    return 0;
}

