package org.apache.ignite.examples;

import java.util.Collections;
import java.util.LinkedHashMap;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteBinary;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteException;
import org.apache.ignite.Ignition;
import org.apache.ignite.binary.BinaryObject;
import org.apache.ignite.binary.BinaryObjectBuilder;
import org.apache.ignite.cache.QueryEntity;
import org.apache.ignite.configuration.CacheConfiguration;

public class BinaryObjectQueryExample {
    private static final String PERSON_TYPE_NAME = "Person";

    public static void main(String[] args) throws IgniteException {
        Ignite ignite = Ignition.start("examples/config/example-ignite.xml");

        CacheConfiguration<Integer, BinaryObject> cacheCfg = new CacheConfiguration<>("peopleCache");
        cacheCfg.setSqlSchema("PUBLIC");
        cacheCfg.setQueryEntities(Collections.singleton(createPersonQueryEntity()));

        IgniteCache<Integer, BinaryObject> cache = ignite.getOrCreateCache(cacheCfg).withKeepBinary();

        cache.put(1, constructPeson("John", 35, ignite.binary()));
        cache.put(2, constructPeson("Mike", 27, ignite.binary()));
    }

    private static QueryEntity createPersonQueryEntity() {
        QueryEntity qe = new QueryEntity(Integer.class.getName(), PERSON_TYPE_NAME);
        qe.setTableName("people");

        LinkedHashMap<String, String> fields = new LinkedHashMap<>();
        fields.put("id", Integer.class.getName());
        fields.put("name", String.class.getName());
        fields.put("age", Integer.class.getName());

        qe.setKeyFieldName("id");

        qe.setFields(fields);

        return qe;
    }

    private static BinaryObject constructPeson(String name, int age, IgniteBinary binary) {
        BinaryObjectBuilder bldr = binary.builder(PERSON_TYPE_NAME);

        bldr.setField("name", name);
        bldr.setField("age", age);

        return bldr.build();
    }
}
