// Copyright (c) 2016, 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 <pthread.h>
#include <unistd.h>

/* Reply callback for blocking command HELLO.BLOCK */
int HelloBlock_Reply(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);
    int *myint = RedictModule_GetBlockedClientPrivateData(ctx);
    return RedictModule_ReplyWithLongLong(ctx,*myint);
}

/* Timeout callback for blocking command HELLO.BLOCK */
int HelloBlock_Timeout(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);
    return RedictModule_ReplyWithSimpleString(ctx,"Request timedout");
}

/* Private data freeing callback for HELLO.BLOCK command. */
void HelloBlock_FreeData(RedictModuleCtx *ctx, void *privdata) {
    REDICTMODULE_NOT_USED(ctx);
    RedictModule_Free(privdata);
}

/* The thread entry point that actually executes the blocking part
 * of the command HELLO.BLOCK. */
void *HelloBlock_ThreadMain(void *arg) {
    void **targ = arg;
    RedictModuleBlockedClient *bc = targ[0];
    long long delay = (unsigned long)targ[1];
    RedictModule_Free(targ);

    sleep(delay);
    int *r = RedictModule_Alloc(sizeof(int));
    *r = rand();
    RedictModule_UnblockClient(bc,r);
    return NULL;
}

/* An example blocked client disconnection callback.
 *
 * Note that in the case of the HELLO.BLOCK command, the blocked client is now
 * owned by the thread calling sleep(). In this specific case, there is not
 * much we can do, however normally we could instead implement a way to
 * signal the thread that the client disconnected, and sleep the specified
 * amount of seconds with a while loop calling sleep(1), so that once we
 * detect the client disconnection, we can terminate the thread ASAP. */
void HelloBlock_Disconnected(RedictModuleCtx *ctx, RedictModuleBlockedClient *bc) {
    RedictModule_Log(ctx,"warning","Blocked client %p disconnected!",
        (void*)bc);

    /* Here you should cleanup your state / threads, and if possible
     * call RedictModule_UnblockClient(), or notify the thread that will
     * call the function ASAP. */
}

/* HELLO.BLOCK <delay> <timeout> -- Block for <count> seconds, then reply with
 * a random number. Timeout is the command timeout, so that you can test
 * what happens when the delay is greater than the timeout. */
int HelloBlock_RedictCommand(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    if (argc != 3) return RedictModule_WrongArity(ctx);
    long long delay;
    long long timeout;

    if (RedictModule_StringToLongLong(argv[1],&delay) != REDICTMODULE_OK) {
        return RedictModule_ReplyWithError(ctx,"ERR invalid count");
    }

    if (RedictModule_StringToLongLong(argv[2],&timeout) != REDICTMODULE_OK) {
        return RedictModule_ReplyWithError(ctx,"ERR invalid count");
    }

    pthread_t tid;
    RedictModuleBlockedClient *bc = RedictModule_BlockClient(ctx,HelloBlock_Reply,HelloBlock_Timeout,HelloBlock_FreeData,timeout);

    /* Here we set a disconnection handler, however since this module will
     * block in sleep() in a thread, there is not much we can do in the
     * callback, so this is just to show you the API. */
    RedictModule_SetDisconnectCallback(bc,HelloBlock_Disconnected);

    /* Now that we setup a blocking client, we need to pass the control
     * to the thread. However we need to pass arguments to the thread:
     * the delay and a reference to the blocked client handle. */
    void **targ = RedictModule_Alloc(sizeof(void*)*2);
    targ[0] = bc;
    targ[1] = (void*)(unsigned long) delay;

    if (pthread_create(&tid,NULL,HelloBlock_ThreadMain,targ) != 0) {
        RedictModule_AbortBlock(bc);
        return RedictModule_ReplyWithError(ctx,"-ERR Can't start thread");
    }
    return REDICTMODULE_OK;
}

/* The thread entry point that actually executes the blocking part
 * of the command HELLO.KEYS.
 *
 * Note: this implementation is very simple on purpose, so no duplicated
 * keys (returned by SCAN) are filtered. However adding such a functionality
 * would be trivial just using any data structure implementing a dictionary
 * in order to filter the duplicated items. */
void *HelloKeys_ThreadMain(void *arg) {
    RedictModuleBlockedClient *bc = arg;
    RedictModuleCtx *ctx = RedictModule_GetThreadSafeContext(bc);
    long long cursor = 0;
    size_t replylen = 0;

    RedictModule_ReplyWithArray(ctx,REDICTMODULE_POSTPONED_LEN);
    do {
        RedictModule_ThreadSafeContextLock(ctx);
        RedictModuleCallReply *reply = RedictModule_Call(ctx,
            "SCAN","l",(long long)cursor);
        RedictModule_ThreadSafeContextUnlock(ctx);

        RedictModuleCallReply *cr_cursor =
            RedictModule_CallReplyArrayElement(reply,0);
        RedictModuleCallReply *cr_keys =
            RedictModule_CallReplyArrayElement(reply,1);

        RedictModuleString *s = RedictModule_CreateStringFromCallReply(cr_cursor);
        RedictModule_StringToLongLong(s,&cursor);
        RedictModule_FreeString(ctx,s);

        size_t items = RedictModule_CallReplyLength(cr_keys);
        for (size_t j = 0; j < items; j++) {
            RedictModuleCallReply *ele =
                RedictModule_CallReplyArrayElement(cr_keys,j);
            RedictModule_ReplyWithCallReply(ctx,ele);
            replylen++;
        }
        RedictModule_FreeCallReply(reply);
    } while (cursor != 0);
    RedictModule_ReplySetArrayLength(ctx,replylen);

    RedictModule_FreeThreadSafeContext(ctx);
    RedictModule_UnblockClient(bc,NULL);
    return NULL;
}

/* HELLO.KEYS -- Return all the keys in the current database without blocking
 * the server. The keys do not represent a point-in-time state so only the keys
 * that were in the database from the start to the end are guaranteed to be
 * there. */
int HelloKeys_RedictCommand(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    if (argc != 1) return RedictModule_WrongArity(ctx);

    pthread_t tid;

    /* Note that when blocking the client we do not set any callback: no
     * timeout is possible since we passed '0', nor we need a reply callback
     * because we'll use the thread safe context to accumulate a reply. */
    RedictModuleBlockedClient *bc = RedictModule_BlockClient(ctx,NULL,NULL,NULL,0);

    /* Now that we setup a blocking client, we need to pass the control
     * to the thread. However we need to pass arguments to the thread:
     * the reference to the blocked client handle. */
    if (pthread_create(&tid,NULL,HelloKeys_ThreadMain,bc) != 0) {
        RedictModule_AbortBlock(bc);
        return RedictModule_ReplyWithError(ctx,"-ERR Can't start thread");
    }
    return REDICTMODULE_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,"helloblock",1,REDICTMODULE_APIVER_1)
        == REDICTMODULE_ERR) return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"hello.block",
        HelloBlock_RedictCommand,"",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;
    if (RedictModule_CreateCommand(ctx,"hello.keys",
        HelloKeys_RedictCommand,"",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    return REDICTMODULE_OK;
}
