#include <stdlib.h>
#include <string.h>
#include "linkedlist.h"

// Create a new node with copies of key and value.
// We use strdup so the node owns its own memory.
node *create_node(const char *key, const char *value)
{
    node *n = (node *)malloc(sizeof(node));
    n->key = strdup(key);
    n->value = strdup(value);
    n->next = NULL;
    return n;
}

// Insert a (key, value) pair at the head of the list.
// If the key already exists, update the value.
// Return the new head of the list.
node *list_insert(node *head, const char *key, const char *value)
{
    // First check if the key already exists
    node *cur = head;
    while (cur != NULL) {
        if (strcmp(cur->key, key) == 0) {
            // Key found -- update the value
            free(cur->value);
            cur->value = strdup(value);
            return head;
        }
        cur = cur->next;
    }

    // Key not found -- prepend a new node (O(1))
    node *n = create_node(key, value);
    n->next = head;
    return n;
}

// Search for a key in the list.
// Return the value if found, NULL otherwise.
char *list_search(node *head, const char *key)
{
    node *cur = head;
    while (cur != NULL) {
        if (strcmp(cur->key, key) == 0) {
            return cur->value;
        }
        cur = cur->next;
    }
    return NULL;
}

// Free the entire list
void list_destroy(node *head)
{
    node *cur = head;
    while (cur != NULL) {
        node *next = cur->next;
        free(cur->key);
        free(cur->value);
        free(cur);
        cur = next;
    }
}
