#include "SDL3/SDL_events.h"
#include "SDL3/SDL_mouse.h"
#include "Shared.h"
#include "Window.h"
#include <SDL3/SDL.h>
#include <cstdio>

void EngineWindow::Startup(SharedWindowData& shared)
{
    if (!SDL_Init(SDL_INIT_VIDEO))
    {
        printf("Failed to init SDL!\n");
        return;
    }
    Window = SDL_CreateWindow("SDL", shared.WindowWidth, shared.WindowHeight, SDL_WINDOW_RESIZABLE);
    if (Window == nullptr)
    {
        printf("Failed to init SDL Window!\n");
        return;
    }
    auto props = SDL_GetWindowProperties(Window);
    SDL_EnumerateProperties(
        props, [](void*, SDL_PropertiesID id, const char* name) { printf("Prop: %s\n", name); }, nullptr);
    shared.Handle = SDL_GetPointerProperty(props, "SDL.window.win32.hwnd", nullptr);
    if (shared.Handle == nullptr)
    {
        printf("Failed to get window pointer!\n");
        return;
    }
    shared.SDLWindow = Window;
}

void EngineWindow::Update(SharedWindowData& shared)
{
    START_PERF();
    shared.SDLEvents = &EventBuffer[0];

    SDL_Event evt;
    while (SDL_PollEvent(&evt))
    {
        if (shared.SDLEventCount < MaxEventBufferSize)
        {
            EventBuffer[shared.SDLEventCount] = evt;
            ++shared.SDLEventCount;
        }
        else
        {
            printf("Warning: Skipping SDL event!\n");
        }

        switch (evt.type)
        {
        case SDL_EVENT_WINDOW_RESIZED:
        {
            SDL_GetWindowSize(Window, &shared.WindowWidth, &shared.WindowHeight);
            break;
        }
        case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
        {
            CloseRequested = true;
            break;
        }
        case SDL_EVENT_KEY_DOWN:
        {
            shared.HeldScanCodes[evt.key.scancode] = true;
            break;
        }
        case SDL_EVENT_KEY_UP:
        {
            shared.HeldScanCodes[evt.key.scancode] = false;
            break;
        }
        case SDL_EVENT_MOUSE_MOTION:
        {
            break;
        }
        case SDL_EVENT_MOUSE_BUTTON_DOWN:
        {
            shared.HeldMouseButtons[evt.button.button] = true;
            break;
        }
        case SDL_EVENT_MOUSE_BUTTON_UP:
        {
            shared.HeldMouseButtons[evt.button.button] = false;
            break;
        }
        default:
            break;
        }
    }
    SDL_GetRelativeMouseState(&shared.MouseDeltaX, &shared.MouseDeltaY);

    END_PERF(shared.PerfCounters, PerfCounterType::WindowEvents, shared.FrameCounter);
}

void EngineWindow::Shutdown()
{
    SDL_Quit();
}
