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

import java.util.List;
import java.util.function.Consumer;

import org.apache.ignite.Ignition;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.client.ClientCache;
import org.apache.ignite.client.ClientCacheConfiguration;
import org.apache.ignite.client.IgniteClient;
import org.apache.ignite.configuration.ClientConfiguration;

public class TestFunctional {
    private static Integer get(ClientCache<String,Integer> cache, String key) {
        List<List<?>> res = cache.query(new SqlFieldsQuery("SELECT cvalue FROM functional_cache WHERE ckey = ?").setSchema("PUBLIC").setArgs(key)).getAll();
        if(res.size() > 0) {
            return (Integer)res.get(0).get(0);
        } else {
            return null;
        }
    }
    private static void put(ClientCache<String,Integer> cache, String key, Integer value) {
        cache.query(new SqlFieldsQuery("MERGE INTO functional_cache(ckey,cvalue) VALUES(?,?)").setSchema("PUBLIC").setArgs(key, value)).getAll();
    }
    private static void remove(ClientCache<String,Integer> cache, String key) {
        cache.query(new SqlFieldsQuery("DELETE FROM functional_cache WHERE ckey = ?").setSchema("PUBLIC").setArgs(key)).getAll();
    }
    private static void listall(ClientCache<String,Integer> cache, Consumer<List<?>> f) {
        cache.query(new SqlFieldsQuery("SELECT ckey,cvalue FROM functional_cache").setSchema("PUBLIC")).forEach(f);
    }
    private static void test(ClientCache<String,Integer> cache) throws InterruptedException {
        // basic put, get and remove
        put(cache, "v", 123);
        System.out.println(get(cache, "v"));
        remove(cache, "v");
        System.out.println(get(cache, "v"));
        put(cache, "v", 123);
        System.out.println(get(cache, "v"));
        // persistence
        Integer counter = get(cache, "counter");
        if(counter == null) {
            counter = 0;
        }
        counter++;
        System.out.println(counter);
        put(cache, "counter", counter);
        // list all
        listall(cache, row -> { System.out.printf("%s = %d\n",  row.get(0), row.get(1)); });
        // listener not supported using thin
    }
    public static void main(String[] args) throws Exception {
        ClientConfiguration cfg = new ClientConfiguration().setAddresses("localhost:10800");
        IgniteClient cli = Ignition.startClient(cfg);
        ClientCache<String,Integer> cache = cli.getOrCreateCache(new ClientCacheConfiguration().setName("dummy"));
        cache.query(new SqlFieldsQuery("CREATE TABLE IF NOT EXISTS functional_cache (ckey VARCHAR(16) NOT NULL, cvalue INTEGER NOT NULL, PRIMARY KEY(ckey))").setSchema("PUBLIC")).getAll();
        test(cache);
        cli.close();
    }
}
