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

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.BTreeMap;

public class Test2 {
    private static void dump(Map<String,Data> db, String key) throws ClassNotFoundException, IOException {
        System.out.printf("Key=%s\n", key);
        Data value = db.get(key);
        if(value != null) {
            System.out.println(value);
        } else {
            System.out.println("Not found");
        }
    }
    private static final int NREC = 1000;
    public static void main(String[] args) throws IOException, ClassNotFoundException {
    	DB dbf = DBMaker.fileDB("/work/test2db.mdb").make();
		@SuppressWarnings("unchecked")
		Map<String,Data> db = (Map<String, Data>) dbf.treeMap("data").createOrOpen();
        // put data
        for(int i = 0; i < NREC; i++) {
            String key = "Key#" + (1000 + 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(key, value);
        }
        //
        String key;
        key = "Key#" + 1077;
        // get
        dump(db, key);
        // delete
        db.remove(key);
        // get non existing
        dump(db, key);
        //
        key = "Key#" + 1088;
        // update and get
        dump(db, key);
        Data value = db.get(key);
        value.setIv(value.getIv() + 1);
        value.setXv(value.getXv() + 0.1);
        value.setSv(value.getSv() + " updated");
        db.put(key, value);
        dump(db, key);
        // list all
        Iterator<String> it = db.keySet().iterator();
        int n = 0;
        while(it.hasNext()) {
            String itkey = it.next();
            if(!itkey.startsWith("Key#")) {
                System.out.println("Unexpected key: " + itkey);
            }
            Data itvalue = db.get(itkey);
            if(itvalue.getIv() < 1 || NREC < itvalue.getIv()) {
                System.out.println("Unexpected value :" + itvalue);
            }
            n++;
        }
        System.out.println(n);
        // list keys where "Key#1075" <= key < "Key#1085"
        Iterator<String> it2 = ((BTreeMap<String,Data>)db).subMap("Key#1075", "Key#1085").keySet().iterator();
        int n2 = 0;
        while(it2.hasNext()) {
            String it2key = it2.next();
            @SuppressWarnings("unused")
			Data it2value = db.get(it2key);
            n2++;
        }
        System.out.println(n2);
        // close database
        dbf.close();
    }
}
