#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

#include <hiredis.h>
#include <async.h>
#include <adapters/libev.h>

void getCallback(redisAsyncContext *c, void *r, void *privdata) {
    redisReply *reply = r;
    if (reply == NULL) return;

    if(reply->type == REDIS_REPLY_ARRAY)
    {
        for(int i = 0; i != reply -> elements; ++i)
        {
            printf("argv: %s\n", reply->element[i] -> str);
        }
    }
    else
    {
        printf("argv: %s\n", reply->str);
    }

    /* Disconnect after receiving the reply to GET */
    redisAsyncDisconnect(c);
}

void connectCallback(const redisAsyncContext *c, int status) {
    if (status != REDIS_OK) {
        printf("Error: %s\n", c->errstr);
        return;
    }
    printf("Connected...\n");
}

void disconnectCallback(const redisAsyncContext *c, int status) {
    if (status != REDIS_OK) {
        printf("Error: %s\n", c->errstr);
        return;
    }
    printf("Disconnected...\n");
}

int main (int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);

    redisAsyncContext *c = redisAsyncConnect("192.168.24.34", 6379);
    if (c->err) {
        /* Let *c leak for now... */
        printf("Error: %s\n", c->errstr);
        return 1;
    }

    redisLibevAttach(EV_DEFAULT_ c);
    redisAsyncSetConnectCallback(c,connectCallback);
    redisAsyncSetDisconnectCallback(c,disconnectCallback);
    redisAsyncCommand(c, getCallback, NULL, "AUTH ZwLBs_Redis@8F3!");
    redisAsyncCommand(c, getCallback, NULL, "SELECT 5");
    redisAsyncCommand(c, getCallback, NULL, "HGETALL 0f1aed33-4801-45dc-9e8e-e7086ccf4bc4");
    ev_loop(EV_DEFAULT_ 0);
    return 0;
}
