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

#include "hmap.h"



struct hmap *hmap_create(void) {
    struct hmap *m = malloc(sizeof(struct hmap));
    m->nbuckets = 4;
    m->size = 0;
    m->buckets = calloc(m->nbuckets, sizeof(struct hnode *));
    return m;
}

unsigned long hash_str(const char *s) {
    unsigned long h = 5381;
    int c;
    while ((c = (unsigned char)*s++)) h = ((h << 5) + h) + c;
    return h;
}

void hmap_resize(struct hmap *m, int new_n) {
    struct hnode **nb = calloc(new_n, sizeof(struct hnode *));
    for (int i = 0; i < m->nbuckets; i++) {
        struct hnode *e = m->buckets[i];
        while (e) {
            struct hnode *next = e->next;
            unsigned long b = hash_str(e->key) % new_n;
            e->next = nb[b];
            nb[b] = e;
            e = next;
        }
    }
    free(m->buckets);
    m->buckets = nb;
    m->nbuckets = new_n;
}

void hmap_put(struct hmap *m, const char *key, int value) {
    // TODO: update in place if key exists; else insert at bucket head, bump
    //       m->size, and if m->size > m->nbuckets print the resize line and
    //       call hmap_resize(m, m->nbuckets * 2).
    (void)m; (void)key; (void)value;
}

int hmap_get(struct hmap *m, const char *key, int *found) {
    // TODO: walk the bucket chain; set *found and return the value, or set
    //       *found = 0 and return 0.
    (void)m; (void)key;
    *found = 0;
    return 0;
}

int hmap_delete(struct hmap *m, const char *key) {
    // TODO: unlink and free the matching node, decrement m->size, return 1;
    //       return 0 if the key is absent.
    (void)m; (void)key;
    return 0;
}


int main(void) {
    struct hmap *m = hmap_create();
    char cmd[32], key[128];
    int v;
    while (scanf("%31s", cmd) == 1) {
        if (strcmp(cmd, "put") == 0) {
            if (scanf("%127s %d", key, &v) != 2) break;
            hmap_put(m, key, v);
            printf("put %s = %d\n", key, v);
        } else if (strcmp(cmd, "get") == 0) {
            if (scanf("%127s", key) != 1) break;
            int found;
            int r = hmap_get(m, key, &found);
            if (found) printf("get %s -> %d\n", key, r);
            else printf("get %s -> (not found)\n", key);
        } else if (strcmp(cmd, "del") == 0) {
            if (scanf("%127s", key) != 1) break;
            printf("del %s -> %s\n", key, hmap_delete(m, key) ? "ok" : "absent");
        } else if (strcmp(cmd, "size") == 0) {
            printf("size = %d\n", m->size);
        }
    }
    return 0;
}
