/*****************************************************************************
    This code will test whether hash tables entries can be inserted correctly,
    and retrieved correctly.
 
    NOTE: Add code to test whether duplicates are handled correctly (use a
    small hash table and lots of keys).
 *****************************************************************************/
#include <stdio.h>
#include <string.h>
#include "pslib.h"
#include "psTest.h"
#include "psHash.h"
#define NUM_HASH_TABLE_BUCKETS 100
int imGlobal = 0;

typedef struct
{
    char *name;
}
ID;
static void IdFree(ID *id);

static ID *IdAlloc(const char *name)
{
    ID *id = psAlloc(sizeof(ID));
    p_psMemSetDeallocator(id,(psFreeFcn)IdFree);
    id->name = psStringCopy(name);

    return id;
}

static void IdFree(ID *id)
{
    imGlobal++;
    psFree(id->name);
}

int main()
{
    psHash *myHashTable = NULL;
    int testStatus      = true;
    int i               = 0;
    ID *id = NULL;
    char *myKeys[] = {"ENTRY00", "ENTRY01", "ENTRY02", "ENTRY03", NULL
                     };
    char *myData[] = {"IDA", "IDB", "IDC", "IDD", NULL
                     };
    int currentId = psMemGetId();
    int memLeaks        = 0;

    printPositiveTestHeader(stdout,
                            "psHash functions",
                            "psHashAdd()");

    myHashTable = psHashAlloc(NUM_HASH_TABLE_BUCKETS);
    i = 0;
    while (myKeys[i] != NULL) {
        id = IdAlloc(myData[i]);
        psHashAdd(myHashTable, myKeys[i], id);
        psFree(id);
        i++;
    }

    i = 0;
    while (myKeys[i] != NULL) {
        id = psHashLookup(myHashTable, myKeys[i]);
        if (0 != strcmp(myData[i], id->name)) {
            fprintf(stderr, "%s: Hash table entry for key %s was %s (should be %s).\n",
                    __func__, myKeys[i], id->name, myData[i]);
        }
        i++;
    }
    id = psHashLookup(myHashTable, "BogusKey");
    if (id != NULL) {
        fprintf(stderr, "%s: Hash table entry for key %s was not NULL.\n",
                __func__, "BogusKey");
    }

    //    psHashFree(myHashTable, NULL);
    psFree(myHashTable);

    memLeaks = psMemCheckLeaks(currentId,NULL,stderr);
    if (0 != memLeaks) {
        psAbort(__func__,"Memory Leaks! (%d leaks)", memLeaks);
    }
    psMemCheckCorruption(1);

    printFooter(stdout,
                "psHash functions",
                "psHashAdd()",
                testStatus);

    return (!testStatus);
}
