//-----------------------------------------------------------------
// Game Engine WinMain Function
// C++ Source - GameWinMain.cpp - version v8_01
//-----------------------------------------------------------------

//-----------------------------------------------------------------
// Include Files
//-----------------------------------------------------------------
#define _WIN32_WINNT 0x0A00				// Windows 10 or 11
#define _WINSOCKAPI_
#include <windows.h>
#include <windowsx.h>
#include <stdlib.h>
#include <tchar.h>
#include <Mmsystem.h>					// winmm.lib header, used for playing sound
#undef MessageBox

#include "GameWinMain.h"
#include "GameEngine.h"

#include "Game.h"

//-----------------------------------------------------------------
// Create GAME_ENGINE global (singleton) object and pointer
//-----------------------------------------------------------------
GameEngine myGameEngine;
GameEngine* GAME_ENGINE{ &myGameEngine };


void AllocateConsole()
{
    if (AllocConsole())                          // Allocate a new console for the application
    {
        FILE *fp;                                // Redirect STDOUT to the console
        freopen_s(&fp, "CONOUT$", "w", stdout);
        setvbuf(stdout, NULL, _IONBF, 0);        // Disable buffering for stdout

        freopen_s(&fp, "CONOUT$", "w", stderr);  // Redirect STDERR to the console
        setvbuf(stderr, NULL, _IONBF, 0);        // Disable buffering for stderr

        freopen_s(&fp, "CONIN$", "r", stdin);    // Redirect STDIN to the console
        setvbuf(stdin, NULL, _IONBF, 0);         // Disable buffering for stdin

        std::ios::sync_with_stdio(true);         // Sync C++ streams with the console
    }
}

std::string WStringToString(const std::wstring& wstr) {
    if (wstr.empty()) return {};

    int size_needed = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, nullptr, 0, nullptr, nullptr);
    std::string str(size_needed - 1, '\0');
    WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &str[0], size_needed, nullptr, nullptr);
    return str;
}


//-----------------------------------------------------------------
// Main Function
//-----------------------------------------------------------------
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
{
    AllocateConsole();

    int argc{ 1 };
    LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
    if(argc == 2){
        //We dragged and Dropped a lua file on us
        std::string convertedString{WStringToString(argv[1])};
        std::cout << "Loading file: " << convertedString << std::endl;
        GAME_ENGINE->SetGame(new Game(convertedString));					// any class that implements AbstractGame

    } else {
	    GAME_ENGINE->SetGame(new Game("./Pong.lua"));					// any class that implements AbstractGame
    }


	return GAME_ENGINE->Run(hInstance, nCmdShow);		// here we go

}

