// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package nosql.rocksdb;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import org.rocksdb.RocksDB;
import org.rocksdb.RocksDBException;
import org.rocksdb.RocksIterator;

public class Test {
    private static byte[] prep(String key) throws UnsupportedEncodingException {
        return key.getBytes("UTF-8");
    }
    private static byte[] serialize(Data o) throws IOException {
        ByteBuffer bb = ByteBuffer.allocate(1000);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.putInt(o.getIv());
        bb.putDouble(o.getXv());
        byte[] b = o.getSv().getBytes("UTF-8");
        bb.putShort((short)b.length);
        bb.put(b);
        int n = bb.position();
        byte[] res = new byte[n];
        bb.rewind();
        bb.get(res);
        return res;
    }
    private static Data deserialize(byte[] b) throws IOException, ClassNotFoundException {
        ByteBuffer bb = ByteBuffer.wrap(b);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        int iv = bb.getInt();
        double xv = bb.getDouble();
        int len = bb.getShort();
        byte[] temp = new byte[len];
        bb.get(temp);
        String sv = new String(temp, "UTF-8");
        Data res = new Data(iv, xv, sv);
        return res;
    }
    private static void dump(RocksDB db, String key) throws ClassNotFoundException, IOException, RocksDBException {
        System.out.printf("Key=%s\n", key);
        byte[] rawvalue = db.get(prep(key));
        if(rawvalue != null) {
            Data value = deserialize(rawvalue);
            System.out.println(value);
        } else {
            System.out.println("Not found");
        }
    }
    private static final int NREC = 1000;
    private static final int JAVA_OFFSET = 2 * NREC;
    public static void main(String[] args) throws RocksDBException, IOException, ClassNotFoundException {
        RocksDB.loadLibrary();
        try(RocksDB db = RocksDB.open("/work/R/DB")) {
            // put data
            for(int i = 0; i < NREC; i++) {
                String key = "Key#" + (JAVA_OFFSET + i + 1);
                Data value = new Data();
                value.setIv(i + 1);
                value.setXv(i + 1.0);
                value.setSv(String.format("This is value %d", i + 1));
                db.put(prep(key), serialize(value));
            }
            //
            String key;
            key = "Key#" + (JAVA_OFFSET + 77);
            // get
            dump(db, key);
            // delete
            db.delete(prep(key));
            // get non existing
            dump(db, key);
            //
            key = "Key#" + (JAVA_OFFSET + 88);
            // update and get
            dump(db, key);
            Data value = (Data)deserialize(db.get(prep(key)));
            value.setIv(value.getIv() + 1);
            value.setXv(value.getXv() + 0.1);
            value.setSv(value.getSv() + " updated");
            db.put(prep(key), serialize(value));
            dump(db, key);
            // list all
            try(RocksIterator it = db.newIterator()) {
                it.seekToFirst();
                int n = 0;
                while(it.isValid()) {
                    String itkey = new String(it.key(), "UTF-8");
                    if(!itkey.startsWith("Key#")) {
                        System.out.println("Unexpected key: " + itkey);
                    }
                    Data itvalue = (Data)deserialize(db.get(prep(itkey)));
                    if(itvalue.getIv() < 1 || NREC < itvalue.getIv()) {
                        System.out.println("Unexpected value :" + itvalue);
                    }
                    n++;
                    it.next();
                }
                System.out.println(n);
            }
            // list keys where "Key#n075" <= key < "Key#n085"
            try(RocksIterator it2 = db.newIterator()) {
                it2.seek(prep("Key#" + (JAVA_OFFSET + 75)));
                int n2 = 0;
                while(it2.isValid()) {
                    String it2key = new String(it2.key());
                    if(it2key.compareTo("Key#" + (JAVA_OFFSET + 85)) >= 0) break;
                    n2++;
                    it2.next();
                }
                System.out.println(n2);
            }
        }
    }
}
