#include "render.h"
#include "engine_global.h"
#include "scene.h"
#include "utils/debug.h"
#include "utils/list.h"

static List g_render_objects = {}; //!< List of all registered rendering objects

void InitializeRenderingSubsystem() {
    g_render_objects = list_from_type(Renderable);
}

void CleanupRenderingSubsystem() {
    list_empty(&g_render_objects);
}

void AddRenderable(Renderable renderable) {
    ASSERT_RETURN(list_find(&g_render_objects, &renderable) == g_render_objects.len,, "AddRenderable: Argument is already registered, cannot register twice");
    list_add(&g_render_objects, &renderable);
}

void RemoveRenderable(Renderable renderable) {
    size_t idx = list_find(&g_render_objects, &renderable);
    ASSERT_RETURN(idx != g_render_objects.len,, "RemoveRenderable: Argument is not registered, cannot unregister.");
    list_erase(&g_render_objects, idx);
}

void RenderNextFrame() {
    BeginDrawing();
    ClearBackground(DARKGRAY);
    CameraNode *camera = GetMainScene()->main_camera;
    if(camera != NULL) { // can't draw anything if there is no camera
        BeginMode3D(CameraNodeGetCamera(camera));
        list_foreach(Renderable *,object, &g_render_objects)
            object->tc->draw(object->data);
        DrawGrid(100, 1.f);
        EndMode3D();
    } else {
        UNREACHABLE("RenderNextFrame: camera not found.");
    }
    DrawFPS(20, 20);
    EndDrawing();
}
