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

#include <string.h>

static RT_CVAR_S(rt_Renderer, "The used renderer. Available options: dx11.", "dx11");

RT_DLLEXPORT rt_renderer_api g_renderer;

typedef rt_renderer_api rt_load_renderer_impl_fn(void);

#ifdef RT_STATIC_LIB
extern rt_renderer_api rtLoadRendererImpl(void);
#else
static rt_dynlib _renderer_lib;
#endif

RT_DLLEXPORT rt_result rtLoadRenderer(void) {
    rt_load_renderer_impl_fn *LoadRendererImpl = NULL;
    if (!rtGetCVAR("rt_Renderer"))
        rtRegisterCVAR(&rt_Renderer);
#ifdef RT_STATIC_LIB
    LoadRendererImpl = rtLoadRendererImpl;
#else
    const char *dllname = NULL;
    if (strcmp(rt_Renderer.s, "dx11")==0)
        dllname = RT_DLLNAME("rtdx11");
    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;
    }
    LoadRendererImpl = (rt_load_renderer_impl_fn *)rtGetSymbol(_renderer_lib, "rtLoadRendererImpl");
    if (!LoadRendererImpl) {
        rtReportError("RENDERER", "Invalid renderer. Could not find rtLoadRendererImpl");
        return RT_UNKNOWN_ERROR;
    }
#endif
    g_renderer = LoadRendererImpl();
    return RT_SUCCESS;
}
