package net.juniper.cs.constants;

import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.Ignition;
import org.apache.ignite.lang.IgniteCallable;

import net.juniper.cs.Person;
import net.juniper.cs.entity.InstallBase;

public class CacheManager {
	
private static Ignite instance = null;
	
	public static final String CACHE = "TEST_CACHE";
	
	public static Ignite getInstance(){
		if (null == instance){
			synchronized(CacheManager.class){
				if (null == instance){
					instance  = Ignition.ignite("my-grid");; 
				}
			}
		}
		return instance;
	}
	
	
	
	public static IgniteCache<String, Person> getTestCache(String name){
		return getInstance().getOrCreateCache(name);
	}
	
	public static IgniteCache<String, TestPojo> getCache(){
		return getInstance().getOrCreateCache(CACHE);
	}
	
	public static void main(String[] args) {
		URL resource = CacheManager.class.getResource("/ignite.xml");
		Ignition.start(resource);
	
		Ignite ignite = Ignition.ignite("my-grid");
		
		Collection<IgniteCallable<Boolean>> calls = new ArrayList<>();
//		IgniteDataStreamer<Object, Object> dataStreamer = CacheManager.getInstance().dataStreamer(CACHE);
		for (int i = 0; i < 5; i++){
			calls.add(new IgniteCallable<Boolean>() {
		        @Override public Boolean call() throws Exception {
		        	String name = Thread.currentThread().getName();
		        	System.out.println("Current thread "+ Thread.currentThread().getName());
		        	
		        	for (int i = 0; i < 1000000; i++){
//		        		CacheManager.getInstallBaseCache().put(name+"-"+i, new TestPojo());
		        		CacheManager.getInstance().dataStreamer(CACHE).addData(name+"-"+i, new TestPojo());
		        	}
		        	
		        	return true;
		        }
		    });
			
		}
		 
		long start = System.currentTimeMillis();
		// Execute collection of callables on the cluster.
		Collection<Boolean> res = ignite.compute().call(calls);

		System.out.println("Time taken to process "+ (System.currentTimeMillis() - start));
	
	}


}
