// Copyright (c) 2019, 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>

/* Client state change callback. */
void clientChangeCallback(RedictModuleCtx *ctx, RedictModuleEvent e, uint64_t sub, void *data)
{
    REDICTMODULE_NOT_USED(ctx);
    REDICTMODULE_NOT_USED(e);

    RedictModuleClientInfo *ci = data;
    printf("Client %s event for client #%llu %s:%d\n",
        (sub == REDICTMODULE_SUBEVENT_CLIENT_CHANGE_CONNECTED) ?
            "connection" : "disconnection",
        (unsigned long long)ci->id,ci->addr,ci->port);
}

void flushdbCallback(RedictModuleCtx *ctx, RedictModuleEvent e, uint64_t sub, void *data)
{
    REDICTMODULE_NOT_USED(ctx);
    REDICTMODULE_NOT_USED(e);

    RedictModuleFlushInfo *fi = data;
    if (sub == REDICTMODULE_SUBEVENT_FLUSHDB_START) {
        if (fi->dbnum != -1) {
            RedictModuleCallReply *reply;
            reply = RedictModule_Call(ctx,"DBSIZE","");
            long long numkeys = RedictModule_CallReplyInteger(reply);
            printf("FLUSHDB event of database %d started (%lld keys in DB)\n",
                fi->dbnum, numkeys);
            RedictModule_FreeCallReply(reply);
        } else {
            printf("FLUSHALL event started\n");
        }
    } else {
        if (fi->dbnum != -1) {
            printf("FLUSHDB event of database %d ended\n",fi->dbnum);
        } else {
            printf("FLUSHALL event ended\n");
        }
    }
}

/* 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,"hellohook",1,REDICTMODULE_APIVER_1)
        == REDICTMODULE_ERR) return REDICTMODULE_ERR;

    RedictModule_SubscribeToServerEvent(ctx,
        RedictModuleEvent_ClientChange, clientChangeCallback);
    RedictModule_SubscribeToServerEvent(ctx,
        RedictModuleEvent_FlushDB, flushdbCallback);
    return REDICTMODULE_OK;
}
