//
// Created by villuton on 16.09.2025.
//
#include "DeviceStorage.h"

//
// Created by ilya on 18.10.23.
//

#include <CmsisRtosThreadUtils.h>
#include "DeviceStorage.h"
#include "VersionRandID.h"

#define LOGGER env->logger
#define LOG_SIGN "Хран."

#define VARIABLE_GROUP_UNTRACKED 0
#define VARIABLE_GROUP_FLASH (1 << 0)

void DeviceStorage_InitVariablesTable(tDeviceStorage *env) {

    VariablesTableInitStatic(&env->publicVariablesTable, env->mem.vartab);

    DataRuntime_InitDefaults(&env->runtime);

    DataFlash_AddToVarTab(&env->nvm, &env->publicVariablesTable, VARIABLE_GROUP_FLASH);
    DataRuntime_AddToVarTab(&env->runtime, &env->publicVariablesTable, VARIABLE_GROUP_UNTRACKED);
}

bool DeviceStorage_LoadNonVolatile(tDeviceStorage *env) {

    if (VarsTabDumpObserver_Load(&env->dumpObserver)) {
        if (env->nvm.version == DEVICE_DATA_NO_VOLATILE_VERSION) {
            return true;
        }
    }

    DeviceDataNonVolatile_InitDefaults(&env->nvm);

    return VarsTabDumpObserver_Dump(&env->dumpObserver);

}

void DeviceStorage_ForceDump(tDeviceStorage *env) {
    VarsTabDumpObserver_Dump(&env->dumpObserver);
}

void DeviceStorage_InitCommon(tDeviceStorage *env, tStorageInterface *storageInterface) {
    VarsTabDumpObserver_Init(
            &env->dumpObserver,
            storageInterface,
            5000,
            &env->nvm,
            sizeof(env->nvm),
            &env->publicVariablesTable,
            VARIABLE_GROUP_FLASH
    );
    env->dumpObserver.logger = env->logger;

    DeviceStorage_InitVariablesTable(env);
}

void DeviceStorage_InitDefaults(tDeviceStorage *env) {
    DeviceStorage_InitCommon(env, NULL);
    DeviceDataNonVolatile_InitDefaults(&env->nvm);
}

bool DeviceStorage_Init(tDeviceStorage *env, tStorageInterface *storageInterface) {

    DeviceStorage_InitCommon(env, storageInterface);

    return DeviceStorage_LoadNonVolatile(env);
}
