// Copyright (c) 2018, Salvatore Sanfilippo <antirez at gmail dot com>
// SPDX-FileCopyrightText: 2024 Redict Contributors
// SPDX-FileCopyrightText: 2024 Salvatore Sanfilippo <antirez at gmail dot com>
//
// SPDX-License-Identifier: BSD-3-Clause

#include "../redictmodule.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

/* Timer callback. */
void timerHandler(RedictModuleCtx *ctx, void *data) {
    REDICTMODULE_NOT_USED(ctx);
    printf("Fired %s!\n", (char *)data);
    RedictModule_Free(data);
}

/* HELLOTIMER.TIMER*/
int TimerCommand_RedictCommand(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    for (int j = 0; j < 10; j++) {
        int delay = rand() % 5000;
        char *buf = RedictModule_Alloc(256);
        snprintf(buf,256,"After %d", delay);
        RedictModuleTimerID tid = RedictModule_CreateTimer(ctx,delay,timerHandler,buf);
        REDICTMODULE_NOT_USED(tid);
    }
    return RedictModule_ReplyWithSimpleString(ctx, "OK");
}

/* This function must be present on each Redict module. It is used in order to
 * register the commands into the Redict server. */
int RedictModule_OnLoad(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    if (RedictModule_Init(ctx,"hellotimer",1,REDICTMODULE_APIVER_1)
        == REDICTMODULE_ERR) return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"hellotimer.timer",
        TimerCommand_RedictCommand,"readonly",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    return REDICTMODULE_OK;
}
