#include "backend_api.h"
#include "runtime/dynamic_libs.h"
#include "runtime/config.h"
#include "runtime/runtime.h"

#include <string.h>


RT_DLLEXPORT rt_render_backend_api g_render_backend;

typedef rt_render_backend_api rt_load_renderer_impl_fn(void);

#ifdef RT_STATIC_LIB
extern rt_render_backend_api rtLoadRenderBackendImpl(void);
#else
static rt_dynlib _renderer_lib;
#endif

#define DEFAULT_RENDERER "vk"

RT_DLLEXPORT rt_result rtLoadRenderBackend(void) {
    rt_load_renderer_impl_fn *LoadRenderBackendImpl = NULL;
    rt_cvar *l_Renderer = rtGetCVAR("l_Renderer");
    const char *renderer = DEFAULT_RENDERER;
    if (!l_Renderer) {
        rtReportError("RENDERER", "rt_Renderer CVAR is not registered. Falling back to '%s'.", DEFAULT_RENDERER);
    }
    else {
        renderer = l_Renderer->s;
    }
    
#ifdef RT_STATIC_LIB
    RT_UNUSED((void*)renderer);
    LoadRenderBackendImpl = rtLoadRenderBackendImpl;
#else
    const char *dllname = NULL;
    if (strcmp(renderer, "dx11")==0)
        dllname = RT_DLLNAME("rtdx11");
    else if (strcmp(renderer, "vk") == 0)
        dllname = RTODLLNAME("rtvk");
    else {
        rtReportError("RENDERER", "Invalid renderer selected: %s", rt_Renderer.s);
        return RT_INVALID_VALUE;
    }
    _renderer_lib = rtOpenLib(dllname);
    if (!_renderer_lib) {
        rtReportError("RENDERER", "Unable to load renderer backend: %s", dllname);
        return RT_UNKNOWN_ERROR;
    }
    LoadRenderBackendImpl = (rt_load_renderer_impl_fn *)rtGetSymbol(_renderer_lib, "rtLoadRenderBackendImpl");
    if (!LoadRenderBackendImpl) {
        rtReportError("RENDERER", "Invalid renderer. Could not find rtLoadRendererImpl");
        return RT_UNKNOWN_ERROR;
    }
#endif
    g_render_backend = LoadRenderBackendImpl();
    return RT_SUCCESS;
}
