/* 
 * File:   redblacktree.example.associationarray.cpp
 * Author: Pawel Banasiak http://banasiak.net
 * License: BSD
 *
 * Created on 13.12.2008, 00:50
 */

#include <iostream>
#include <string>
#include "redblacktree.h"
using namespace std;

class associationArray {
public:

    typedef struct {
        string key;
        string value;
    } container;
    int static comp(const container*, const container*);
    string & operator[](const string);
    void erase(const string);
    bool isset(const string);
    associationArray();
private:
    redBlackTree<container> *a;
};

void associationArray::erase(const string key) {
    container tmp;
    tmp.key = key;
    tmp.value = "";
    if (this->a->deleteNode(tmp) == this->a->ok) {
        //OK
    } else {
        //ERROR
    }
}

bool associationArray::isset(const string key) {
    container tmp;
    tmp.key = key;
    tmp.value = "";
    if (this->a->findNode(tmp) == 0)
        return false;
    return true;
}

string &associationArray::operator[](const string key) {
    container tmp, *odp;
    tmp.key = key;
    tmp.value = "";
    odp = this->a->findNode(tmp);
    if (odp != 0)
        return odp->value;
    redBlackTree<container>::status status = this->a->insertNode(tmp);
    if (status == this->a->ok) {
        odp = this->a->findNode(tmp);
        return odp->value;
    } else if (status == this->a->badAlloc) {
        //NO MEMORY
    } else {
        //ERROR
    }
}

int associationArray::comp(const container *arg1, const container *arg2) {
    return arg1->key.compare(arg2->key);
}

associationArray::associationArray() {
    try {
        this->a = new redBlackTree <container > (associationArray::comp);
    } catch (...) {
        //ERROR
    }
}

int main() {
    associationArray g;
    g["test"] = "Some text";
    cout << (g.isset("test") ? "TRUE" : "FALSE") << endl;
    cout << g["test"] << endl;
    g.erase("test");
    cout << (g.isset("test") ? "TRUE" : "FALSE") << endl;
    return (EXIT_SUCCESS);
}

