#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "../include/hiredis.h"

redisContext *context;
char *result;
void addnums( int* a, int* b )
{
    int c = (*a) + (*b);  /* convert pointers to values, then add them */
    printf("sum of %i and %i is %i\n", (*a), (*b), c );
}

void initConnection()
{
    context = redisConnect("127.0.0.1", 6379);
    if (context == NULL || context->err) {
        if (context) {
            printf("Error: %s\n", context->errstr);
            // handle error
        } else {
            printf("Can't allocate redis context\n");
        }
    }
}

void setData(char *data)
{
    redisReply *reply;
    // printf("Writing data to redis\n");
    // printf("First char =%c \n",data[0]);
    printf("%zu chars written\n",strlen(data));
    reply = redisCommand(context, "SET data %s",data);
    // printf("data written to redis: %s\n",reply->str);
    freeReplyObject(reply);
}

char *getData(int *len)
{
    redisReply *reply;
    // printf("reading data from redis(c function)\n");
    reply = redisCommand(context, "GET data");
    // printf("data read from redis: %s\n",reply->str);
    
    // printf("reply->str: %s\n",reply->str);
    result = (char*) malloc(strlen(reply->str));
    strcpy(result,reply->str);
    *len = strlen(result);
    freeReplyObject(reply);
    return result;
}

void deallocData()
{
    free(result);
    free(context);
}