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

import java.util.List;

import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;

public class Test3 {
    private static void dump(ODatabaseDocumentTx db, String criteria) {
        System.out.println("dumping " + criteria);
        List<ODocument> rs = db.query(new OSQLSynchQuery<ODocument>("SELECT FROM Order " + criteria));
        for(ODocument d : rs) {
            System.out.println(d.toJSON());
        }
    }
    public static void main(String[] args) {
        // open
    	ODatabaseDocumentTx db = new ODatabaseDocumentTx("remote:192.168.60.129/test3");
    	db.open("admin", "hemmeligt");
((List<ODocument>)db.query(new OSQLSynchQuery<ODocument>("SELECT FROM Order"))).forEach(o -> { o.delete(); }); 
        // setup
        String s1 = "{ \"id\": 1, \"customer\": \"A A\", \"items\": [ { \"no\": 1, \"name\": \"A good Java book\", \"price\": \"19.95\" } ] }";
        System.out.println(s1);
        ODocument d1 = new ODocument("Order");
        d1.fromJSON(s1);
        db.save(d1);
        String s2 = "{ \"id\": 2, \"customer\": \"B B\", \"items\": [ { \"no\": 1, \"name\": \"ASUS MB\", \"price\": \"249.00\" }, " +
                                                                    "{ \"no\": 1, \"name\": \"i5 CPU\", \"price\": \"299.00\", \"note\": \"handle with care\" }, " +
                                                                    "{ \"no\": 1, \"name\": \"4 GB kit\", \"price\": \"249.00\", \"quantity\": 4} ] }";
        System.out.println(s2);
        ODocument d2 = new ODocument("Order");
        d2.fromJSON(s2);
        db.save(d2);
        // query
        dump(db, ""); // all
        dump(db, "WHERE id = 2"); // where id=2
        dump(db, "WHERE customer = 'A A'"); // where customer='A A'
        dump(db, "WHERE customer LIKE 'A%'"); // where customer like 'A%'
        dump(db, "WHERE items CONTAINS(name = 'i5 CPU')"); // where items.name='i5 CPU'
        dump(db, "WHERE items CONTAINS(name LIKE '%Java%')"); // where items.name like '%Java%'
        dump(db, "WHERE id IN [1,2]"); // where id in (1,2)
        dump(db, "WHERE items CONTAINS(note IS NOT NULL)"); // where exists items.note
        // close
        db.close();
    }
}
