// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
#include <iostream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cstring>

using namespace std;

#include "rocksdb/db.h"

using namespace rocksdb;

struct Data
{
    int Iv;
    double Xv;
    char Sv[50];
};

static string Prep(string key)
{
    return key;
}

static void Serialize(Data *d, string *buf)
{
    int slen = strlen(d->Sv);
    buf->resize(4 + 8 + 2 + slen);
    char *p = (char *)buf->data();
    memcpy(p, &d->Iv, 4);
    p += 4;
    memcpy(p, &d->Xv, 8);
    p += 8;
    memcpy(p, &slen, 2);
    p += 2;
    memcpy(p, &d->Sv[0], slen);
}

static void Deserialize(string buf, Data *d)
{
    char *p = (char *)buf.data();
    memcpy(&d->Iv, p, 4);
    p += 4;
    memcpy(&d->Xv, p, 8);
    p += 8;
    int slen;
    memcpy(&slen, p, 2);
    p += 2;
    memcpy(&d->Sv[0], p, slen);
    d->Sv[slen] = '\0';
}

static void check(Status status)
{
    if (!status.ok())
    {
        cout << status.ToString() << endl;
        exit(1);
    }
}

static void Dump(DB *db, string key)
{
    cout << "Key=" << key << endl;
    string rawvalue;
    Status status = db->Get(ReadOptions(), Prep(key), &rawvalue);
    if(status.ok())
    {
        Data value;
        Deserialize(rawvalue, &value);
        cout << "(" << value.Iv << "," << value.Xv << "," << value.Sv << ")" << endl;
    }
    else 
    {
        cout << "Not found" << endl;
    }
}

static string ItoA(int v)
{
    stringstream ss;
    ss << v;
    return ss.str();
}

static const int NREC = 1000;
static const int CPP_OFFSET = NREC;

int main()
{
    Status status;
    DB *db;
    Options options;
    options.create_if_missing = true;
    status = DB::Open(options, "/work/R/DB", &db);
    check(status);
    // put data
    for(int i = 0; i < NREC; i++)
    {
        string key = "Key#" + ItoA(CPP_OFFSET + i + 1);
        Data value;
        value.Iv = i + 1;
        value.Xv = i + 1.0;
        sprintf(value.Sv, "This is value %d", i + 1);
        string temp;
        Serialize(&value, &temp);
        status = db->Put(WriteOptions(), Prep(key), temp);
        check(status);
    }
    //
    string key;
    key = "Key#" + ItoA(CPP_OFFSET + 77);
    // get
    Dump(db, key);
    // delete
    db->Delete(WriteOptions(), Prep(key));
    // get non existing
    Dump(db, key);
    //
    key = "Key#" + ItoA(CPP_OFFSET + 88);
    // update and get
    Dump(db, key);
    string rawvalue;
    status = db->Get(ReadOptions(), Prep(key), &rawvalue);
    Data value;
    Deserialize(rawvalue, &value);
    value.Iv = value.Iv + 1;
    value.Xv = value.Xv + 0.1;
    strcat(value.Sv, " updated");
    string temp;
    Serialize(&value, &temp);
    status = db->Put(WriteOptions(), Prep(key), temp);
    Dump(db, key);
    // list all
    Iterator *it = db->NewIterator(ReadOptions());
    it->SeekToFirst();
    int n = 0;
    while(it->Valid())
    {
        string itkey = it->key().ToString();
        if(itkey.rfind("Key#", 0) != 0)
        {
            cout << "Unexpected key: " << itkey << endl;
        }
        string itrawvalue;
        status = db->Get(ReadOptions(), Prep(itkey), &itrawvalue);
        Data itvalue;
        Deserialize(itrawvalue, &itvalue);
        if (itvalue.Iv < 1 || NREC < itvalue.Iv)
        {
            cout << "Unexpected value :" << "(" << itvalue.Iv << "," << itvalue.Xv << "," << itvalue.Sv << ")" << endl;
        }
        n++;
        it->Next();
    }
    cout << n << endl;
    delete it;
    // list keys where "Key#n075" <= key < "Key#n085"
    Iterator *it2 = db->NewIterator(ReadOptions());
    it2->Seek(Prep("Key#" + ItoA(CPP_OFFSET + 75)));
    int n2 = 0;
    while(it2->Valid())
    {
        string it2key = it2->key().ToString();
        if(it2key >= (string)"Key#" + ItoA(CPP_OFFSET + 85)) break;
        n2++;
        it2->Next();
    }
    cout << n2 << endl;
    delete it2;
    //
    status = db->SyncWAL();
    check(status);
    // This is the correct way of closing but on my Windows 7 it hangs
    //status = db->Close();
    //check(status);
    //delete db;
    exit(0);
}
