#include "runtime.h"
#include "config.h"
#include "aio.h"
#include "file_tab.h"
#include "buffer_manager.h"

extern rt_cvar rt_BufferMemoryBudget;
extern rt_cvar rt_FileTabCapacity;
extern rt_cvar rt_MaxConcurrentAsyncIO;
extern rt_cvar rt_ResourceDirectory;
extern rt_cvar rt_ResourceCacheSize;
extern rt_cvar rt_MaxCachedResources;
extern rt_cvar rt_ResourceNamespaceSize;
extern rt_cvar rt_DisableResourceNamespaceLoad;

void RegisterRuntimeCVars(void) {
    rtRegisterCVAR(&rt_BufferMemoryBudget);
    rtRegisterCVAR(&rt_FileTabCapacity);
    rtRegisterCVAR(&rt_MaxConcurrentAsyncIO);
    rtRegisterCVAR(&rt_ResourceDirectory);
    rtRegisterCVAR(&rt_ResourceCacheSize);
    rtRegisterCVAR(&rt_MaxCachedResources);
    rtRegisterCVAR(&rt_ResourceNamespaceSize);
    rtRegisterCVAR(&rt_DisableResourceNamespaceLoad);
}

extern void SetMainThreadId(void);

extern rt_result InitBufferManager(void);
extern void ShutdownBufferManager(void);
extern rt_result InitFileTab(void);
extern void ShutdownFileTab(void);
extern rt_result InitAIO(void);
extern void ShutdownAIO(void);
extern rt_result InitResourceManager(void);
extern void ShutdownResourceManager(void);
extern rt_result InitTiming(void);

RT_DLLEXPORT rt_result rtInitRuntime(void) {
    SetMainThreadId();
    RegisterRuntimeCVars();

    rt_result res;
    if ((res = InitTiming()) != RT_SUCCESS) {
        rtReportError("TIMING", "Init failed.");
        return res;
    }

    if ((res = InitBufferManager()) != RT_SUCCESS) {
        rtReportError("BUFFERMGR", "Init failed.");
        return res;
    }

    if ((res = InitFileTab()) != RT_SUCCESS) {
        rtReportError("FTAB", "Init failed.");
        return res;
    }

    if ((res = InitAIO()) != RT_SUCCESS) {
        rtReportError("AIO", "Init failed.");
        return res;
    }

    if ((res = InitResourceManager()) != RT_SUCCESS) {
        rtReportError("RESMGR", "Init failed.");
        return res;
    }

    return RT_SUCCESS;
}

RT_DLLEXPORT void rtShutdownRuntime(void) {
    ShutdownResourceManager();
    ShutdownAIO();
    ShutdownFileTab();
    ShutdownBufferManager();
}