// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
import dk.vajhoej.isam.IsamException;
import dk.vajhoej.isam.IsamResult;
import dk.vajhoej.isam.IsamSource;
import dk.vajhoej.isam.Key0;
import dk.vajhoej.isam.local.LocalIsamSource;
import dk.vajhoej.record.RecordException;

public class Test {
    private static void dump(IsamSource db, String id) throws IsamException, RecordException {
        System.out.printf("Key=%s\n", id);
        Data d = db.read(Data.class, new Key0<String>(id));
        if(d != null) {
            System.out.println(d);
        } else {
            System.out.println("Not found");
        }
    }
    private static final int NREC = 1000;
    private static final int JAVA_OFFSET = 6 * NREC;
    public static void main(String[] args) throws IsamException, RecordException {
        try {
            // open
            IsamSource db = new LocalIsamSource("testdb.isq", "dk.vajhoej.bdb.BDB", false);
            // put data
            for(int i = 0; i < NREC; i++) {
                Data d = new Data("Key#" + (JAVA_OFFSET + i + 1), i + 1, i + 1.0, String.format("This is value %d", i + 1));
                db.create(d);
            }
            //
            Data d;
            String id;
            id = "Key#" + (JAVA_OFFSET + 77);
            // get
            dump(db, id);
            // delete
            db.delete(Data.class, new Key0<String>(id));
            // get non existing
            dump(db, id);
            // get and update
            id = "Key#" + (JAVA_OFFSET + 88);
            dump(db, id);
            d = db.read(Data.class, new Key0<String>(id));
            d.setIv(d.getIv() + 1);
            d.setXv(d.getXv() +  0.1);
            d.setSv(d.getSv() + " updated");
            db.update(d);
            dump(db, id);
            // list all
            IsamResult<Data> it = db.readGE(Data.class, new Key0<String>("       "));
            int n = 0;
            while(it.read()) {
                d = it.current();
                if(!d.getId().startsWith("Key#")) {
                    System.out.println("Unexpected key: " + d.getId());
                }
                if(d.getIv() < 1 || NREC < d.getIv()) {
                    System.out.println("Unexpected value :" + d);
                }
                n++;
            }
            System.out.println(n);
            // list keys where "Key#n075" <= key < "Key#n085"
            IsamResult<Data> it2 = db.readGE(Data.class, new Key0<String>("Key#" + (JAVA_OFFSET + 75)));
            int n2 = 0;
            while(it2.read()) {
                d = it2.current();
                if(d.getId().compareTo("Key#" + (JAVA_OFFSET + 85)) >= 0) break;
                n2++;
            }
            System.out.println(n2);
            // close
            db.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
