// SPDX-FileCopyrightText: 2024 Redict Contributors
// SPDX-FileCopyrightText: 2024 Salvatore Sanfilippo <antirez at gmail dot com>
//
// SPDX-License-Identifier: BSD-3-Clause
// SPDX-License-Identifier: LGPL-3.0-only

#include "redictmodule.h"
#include <string.h>
#include <assert.h>
#include <unistd.h>

#define UNUSED(V) ((void) V)

/* Registered type */
RedictModuleType *mallocsize_type = NULL;

typedef enum {
    UDT_RAW,
    UDT_STRING,
    UDT_DICT
} udt_type_t;

typedef struct {
    void *ptr;
    size_t len;
} raw_t;

typedef struct {
    udt_type_t type;
    union {
        raw_t raw;
        RedictModuleString *str;
        RedictModuleDict *dict;
    } data;
} udt_t;

void udt_free(void *value) {
    udt_t *udt = value;
    switch (udt->type) {
        case (UDT_RAW): {
            RedictModule_Free(udt->data.raw.ptr);
            break;
        }
        case (UDT_STRING): {
            RedictModule_FreeString(NULL, udt->data.str);
            break;
        }
        case (UDT_DICT): {
            RedictModuleString *dk, *dv;
            RedictModuleDictIter *iter = RedictModule_DictIteratorStartC(udt->data.dict, "^", NULL, 0);
            while((dk = RedictModule_DictNext(NULL, iter, (void **)&dv)) != NULL) {
                RedictModule_FreeString(NULL, dk);
                RedictModule_FreeString(NULL, dv);
            }
            RedictModule_DictIteratorStop(iter);
            RedictModule_FreeDict(NULL, udt->data.dict);
            break;
        }
    }
    RedictModule_Free(udt);
}

void udt_rdb_save(RedictModuleIO *rdb, void *value) {
    udt_t *udt = value;
    RedictModule_SaveUnsigned(rdb, udt->type);
    switch (udt->type) {
        case (UDT_RAW): {
            RedictModule_SaveStringBuffer(rdb, udt->data.raw.ptr, udt->data.raw.len);
            break;
        }
        case (UDT_STRING): {
            RedictModule_SaveString(rdb, udt->data.str);
            break;
        }
        case (UDT_DICT): {
            RedictModule_SaveUnsigned(rdb, RedictModule_DictSize(udt->data.dict));
            RedictModuleString *dk, *dv;
            RedictModuleDictIter *iter = RedictModule_DictIteratorStartC(udt->data.dict, "^", NULL, 0);
            while((dk = RedictModule_DictNext(NULL, iter, (void **)&dv)) != NULL) {
                RedictModule_SaveString(rdb, dk);
                RedictModule_SaveString(rdb, dv);
                RedictModule_FreeString(NULL, dk); /* Allocated by RedictModule_DictNext */
            }
            RedictModule_DictIteratorStop(iter);
            break;
        }
    }
}

void *udt_rdb_load(RedictModuleIO *rdb, int encver) {
    if (encver != 0)
        return NULL;
    udt_t *udt = RedictModule_Alloc(sizeof(*udt));
    udt->type = RedictModule_LoadUnsigned(rdb);
    switch (udt->type) {
        case (UDT_RAW): {
            udt->data.raw.ptr = RedictModule_LoadStringBuffer(rdb, &udt->data.raw.len);
            break;
        }
        case (UDT_STRING): {
            udt->data.str = RedictModule_LoadString(rdb);
            break;
        }
        case (UDT_DICT): {
            long long dict_len = RedictModule_LoadUnsigned(rdb);
            udt->data.dict = RedictModule_CreateDict(NULL);
            for (int i = 0; i < dict_len; i += 2) {
                RedictModuleString *key = RedictModule_LoadString(rdb);
                RedictModuleString *val = RedictModule_LoadString(rdb);
                RedictModule_DictSet(udt->data.dict, key, val);
            }
            break;
        }
    }

    return udt;
}

size_t udt_mem_usage(RedictModuleKeyOptCtx *ctx, const void *value, size_t sample_size) {
    UNUSED(ctx);
    UNUSED(sample_size);
    
    const udt_t *udt = value;
    size_t size = sizeof(*udt);
    
    switch (udt->type) {
        case (UDT_RAW): {
            size += RedictModule_MallocSize(udt->data.raw.ptr);
            break;
        }
        case (UDT_STRING): {
            size += RedictModule_MallocSizeString(udt->data.str);
            break;
        }
        case (UDT_DICT): {
            void *dk;
            size_t keylen;
            RedictModuleString *dv;
            RedictModuleDictIter *iter = RedictModule_DictIteratorStartC(udt->data.dict, "^", NULL, 0);
            while((dk = RedictModule_DictNextC(iter, &keylen, (void **)&dv)) != NULL) {
                size += keylen;
                size += RedictModule_MallocSizeString(dv);
            }
            RedictModule_DictIteratorStop(iter);
            break;
        }
    }
    
    return size;
}

/* MALLOCSIZE.SETRAW key len */
int cmd_setraw(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    if (argc != 3)
        return RedictModule_WrongArity(ctx);
        
    RedictModuleKey *key = RedictModule_OpenKey(ctx, argv[1], REDICTMODULE_WRITE);

    udt_t *udt = RedictModule_Alloc(sizeof(*udt));
    udt->type = UDT_RAW;
    
    long long raw_len;
    RedictModule_StringToLongLong(argv[2], &raw_len);
    udt->data.raw.ptr = RedictModule_Alloc(raw_len);
    udt->data.raw.len = raw_len;
    
    RedictModule_ModuleTypeSetValue(key, mallocsize_type, udt);
    RedictModule_CloseKey(key);

    return RedictModule_ReplyWithSimpleString(ctx, "OK");
}

/* MALLOCSIZE.SETSTR key string */
int cmd_setstr(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    if (argc != 3)
        return RedictModule_WrongArity(ctx);
        
    RedictModuleKey *key = RedictModule_OpenKey(ctx, argv[1], REDICTMODULE_WRITE);

    udt_t *udt = RedictModule_Alloc(sizeof(*udt));
    udt->type = UDT_STRING;
    
    udt->data.str = argv[2];
    RedictModule_RetainString(ctx, argv[2]);
    
    RedictModule_ModuleTypeSetValue(key, mallocsize_type, udt);
    RedictModule_CloseKey(key);

    return RedictModule_ReplyWithSimpleString(ctx, "OK");
}

/* MALLOCSIZE.SETDICT key field value [field value ...] */
int cmd_setdict(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    if (argc < 4 || argc % 2)
        return RedictModule_WrongArity(ctx);
        
    RedictModuleKey *key = RedictModule_OpenKey(ctx, argv[1], REDICTMODULE_WRITE);

    udt_t *udt = RedictModule_Alloc(sizeof(*udt));
    udt->type = UDT_DICT;
    
    udt->data.dict = RedictModule_CreateDict(ctx);
    for (int i = 2; i < argc; i += 2) {
        RedictModule_DictSet(udt->data.dict, argv[i], argv[i+1]);
        /* No need to retain argv[i], it is copied as the rax key */
        RedictModule_RetainString(ctx, argv[i+1]);   
    }
    
    RedictModule_ModuleTypeSetValue(key, mallocsize_type, udt);
    RedictModule_CloseKey(key);

    return RedictModule_ReplyWithSimpleString(ctx, "OK");
}

int RedictModule_OnLoad(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    UNUSED(argv);
    UNUSED(argc);
    if (RedictModule_Init(ctx,"mallocsize",1,REDICTMODULE_APIVER_1)== REDICTMODULE_ERR)
        return REDICTMODULE_ERR;
        
    RedictModuleTypeMethods tm = {
        .version = REDICTMODULE_TYPE_METHOD_VERSION,
        .rdb_load = udt_rdb_load,
        .rdb_save = udt_rdb_save,
        .free = udt_free,
        .mem_usage2 = udt_mem_usage,
    };

    mallocsize_type = RedictModule_CreateDataType(ctx, "allocsize", 0, &tm);
    if (mallocsize_type == NULL)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx, "mallocsize.setraw", cmd_setraw, "", 1, 1, 1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;
        
    if (RedictModule_CreateCommand(ctx, "mallocsize.setstr", cmd_setstr, "", 1, 1, 1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;
        
    if (RedictModule_CreateCommand(ctx, "mallocsize.setdict", cmd_setdict, "", 1, 1, 1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    return REDICTMODULE_OK;
}
