#include "runtime.h"
#include "config.h"

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#endif

#include <stdio.h>

RT_CVAR_I(rt_AssertEnabled, "Enables or disables asserts in non-release builds. Default: 1", 1);

#define ASSERT_HANDLER_DBGBREAK 0
#define ASSERT_HANDLER_CONTINUE 1

RT_DLLEXPORT int rtAssertHandler(const char *expr, const char *msg, const char *file, int line) {
    if (!rt_AssertEnabled.i)
        return ASSERT_HANDLER_CONTINUE;
    rtLog("ASSERT", "[%s:%d] Assertion (%s) failed: %s", file, line, expr, msg);
#ifdef _WIN32
    char outmessage[512];
    snprintf(outmessage,
             511,
             "Assertion failed: %s\nMessage: %s\n%s:%d\nPress \"Yes\" to debug-break, \"No\" to "
             "continue with asserts enabled or \"Cancel\" to disable asserts.",
             expr,
             msg,
             file,
             line);
    outmessage[511] = '\0';


    DWORD action = MessageBoxA(NULL, outmessage, "Assertion Failed", MB_YESNOCANCEL | MB_ICONERROR);
    if (action == IDYES) {
        return ASSERT_HANDLER_DBGBREAK;
    } else if (action == IDCANCEL) {
        rt_AssertEnabled.i = 0;
    } else if (action != IDNO) {
        rtReportError("CORE", "MessageBoxA for a failed assertion failed.");
        __debugbreak();
        ExitProcess(1);
    }
#endif
    return ASSERT_HANDLER_CONTINUE;
}