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

#include <stdlib.h>

#include <hiredict.h>
#include <async.h>
#include <adapters/glib.h>

static GMainLoop *mainloop;

static void
connect_cb (const redictAsyncContext *ac G_GNUC_UNUSED,
            int status)
{
    if (status != REDICT_OK) {
        g_printerr("Failed to connect: %s\n", ac->errstr);
        g_main_loop_quit(mainloop);
    } else {
        g_printerr("Connected...\n");
    }
}

static void
disconnect_cb (const redictAsyncContext *ac G_GNUC_UNUSED,
               int status)
{
    if (status != REDICT_OK) {
        g_error("Failed to disconnect: %s", ac->errstr);
    } else {
        g_printerr("Disconnected...\n");
        g_main_loop_quit(mainloop);
    }
}

static void
command_cb(redictAsyncContext *ac,
           gpointer r,
           gpointer user_data G_GNUC_UNUSED)
{
    redictReply *reply = r;

    if (reply) {
        g_print("REPLY: %s\n", reply->str);
    }

    redictAsyncDisconnect(ac);
}

gint
main (gint argc     G_GNUC_UNUSED,
      gchar *argv[] G_GNUC_UNUSED)
{
    redictAsyncContext *ac;
    GMainContext *context = NULL;
    GSource *source;

    ac = redictAsyncConnect("127.0.0.1", 6379);
    if (ac->err) {
        g_printerr("%s\n", ac->errstr);
        exit(EXIT_FAILURE);
    }

    source = redict_source_new(ac);
    mainloop = g_main_loop_new(context, FALSE);
    g_source_attach(source, context);

    redictAsyncSetConnectCallback(ac, connect_cb);
    redictAsyncSetDisconnectCallback(ac, disconnect_cb);
    redictAsyncCommand(ac, command_cb, NULL, "SET key 1234");
    redictAsyncCommand(ac, command_cb, NULL, "GET key");

    g_main_loop_run(mainloop);

    return EXIT_SUCCESS;
}
