#include "config.h"
#include "runtime.h"
#include "threading.h"

#include <stddef.h>
#include <string.h>

#define RT_MAX_CVARS 1024

static rt_cvar *_vars[RT_MAX_CVARS];
static unsigned int _next = 0;
static rt_mutex *_mutex   = NULL;

void rtRegisterCVAR(rt_cvar *cvar) {
    /* TODO(Kevin): Check if we have a loaded value for that cvar. 
     * If yes, override the provided default value. */
    if (!_mutex)
        _mutex = rtCreateMutex();
    rtLockMutex(_mutex);
    if (_next < RT_MAX_CVARS) {
        _vars[_next++] = cvar;
    } else {
        rtReportError("cvar", "Ran out of space for CVars");
    }
    rtUnlockMutex(_mutex);
}

rt_cvar *rtGetCVAR(const char *name) {
    if (!_mutex)
        _mutex = rtCreateMutex();
    rt_cvar *var = NULL;
    rtLockMutex(_mutex);
    for (unsigned int i = 0; i < _next; ++i) {
        if (strcmp(name, _vars[i]->name) == 0) {
            var = _vars[i];
            break;
        }
    }
    rtUnlockMutex(_mutex);
    return var;
}