#include <zmq.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

#include "key_value_pair.h"
#include "transfer_defines.h"

#define tolower_str(word) for(int i = 0; i < strlen(word); i++) word[i] = tolower(word[i]);

char *map(char*);
char *reduce(char*);
void rip();

TYPE get_request_type(const char *request)
{
    char type_str[4];
    strncpy(type_str, request, 3);

    if (strcmp(type_str, "map") == 0) return MAP;
    if (strcmp(type_str, "red") == 0) return RED;
    if (strcmp(type_str, "rip") == 0) return RIP;

    return UNSUPPORTED;
}

void main(int argc, char **argv)
{
    // TODO: Start socket with zmq
    // TODO: Wait on calls
    // TODO: Handle calls
    // TODO: Reply to requester

    char *ret;

    switch (get_request_type(argv[1]))
    {
        case MAP:
            perror("Handling MAP\n");
            ret = map(argv[1]);
            break;
        case RED:
            perror("Handling RED\n");
            ret = reduce(argv[1]);
            break;
        case RIP:
            perror("Handling RIP\n");
            rip();
            break;
        case UNSUPPORTED:
            perror("Got unsupported request\n");
            break;
    }

    // TODO: just send ret
}

void add_word(const char *word)
{
    char *word_copy = strdup(word);
    tolower_str(word_copy);

    key_value_pair *kv = init_key_value_pair(word, "1");
    if (kv == NULL)
    {
        fprintf(stderr, "Failed to allocate memory for key: %s\n", word);
        free(word_copy);
        return;
    }
    if (add_key_value_pair(kv) != 0)
    {
        fprintf(stderr, "Failed to add key value: %s\n", word);
        free(word_copy);
        return;
    }

    free(word_copy);
}

char *get_word(const char *request)
{
    static char *iterator = (char*)request;
    int word_length = 0;
    char *word = (char*)malloc(sizeof(char) * 1);
    if (word == NULL) return NULL;
    *word = '\0';

    while (*iterator)
    {
        char *word_bak = word;
        word = (char*)realloc(word, ++word_length);
        if (word == NULL)
        {
            free(word_bak);
            return NULL;
        }
        if (!isalpha(*iterator))
        {
            word[word_length] = '\0';
            return word;
        }
        word[word_length] = *iterator;
        iterator++;
    }
    return NULL;
}

char *map(const char *content)
{
    char *content_iterator = content;


    free_key_value_pairs();
    return NULL;
}

char *reduce(char *content)
{

    free_key_value_pairs();
    return NULL;
}

void rip()
{
    free_key_value_pairs(); // nothing should be allocated
    // TODO: Return RIP on zmq sock;
    perror("---RIP---\n");
    exit(0);
}