package com.libreecm.commonAPI.auxiliars;

import java.util.Iterator;
import java.util.concurrent.TimeUnit;

import org.ehcache.Cache;
import org.ehcache.Cache.Entry;
import org.ehcache.CacheManager;
import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;

import com.libreecm.commonAPI.model.Repository;

public class RepositoryCache {

	private static RepositoryCache instance;
	
	private Cache<String, Repository> myCache ;
	
	private RepositoryCache(Duration timeToLive) {
		//Configure the cache to have max 100 elements, elements disapears at 5 minutes from it's creation
		CacheConfiguration<String, Repository> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, Repository.class,
		        ResourcePoolsBuilder.heap(100)) 
				//.withExpiry(Expirations.timeToLiveExpiration(Duration.of(5, TimeUnit.MINUTES))) 
				.withExpiry(Expirations.timeToLiveExpiration(timeToLive)) 
			    .build();
		
		
		CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
				.withCache("preConfigured", cacheConfiguration)
				.build();
		cacheManager.init();
		
		Cache<String, Repository> preConfigured = cacheManager.getCache("preConfigured", String.class, Repository.class);

		myCache = cacheManager.createCache("myCache", CacheConfigurationBuilder
				.newCacheConfigurationBuilder(String.class, Repository.class, ResourcePoolsBuilder.heap(10)).build());

		//cacheManager.removeCache("preConfigured");

		//cacheManager.close();
	}

	public static RepositoryCache get(Duration timeToLive) {
		if (instance == null)
			instance = new RepositoryCache(timeToLive);
		return instance;
	}
	
	public Repository get(String name){
		return myCache.get(name);
	}
	
	public void set(Repository repository){
		myCache.put(repository.getName(), repository);
	}
	
	public Repository getById(String id){
		Iterator<Entry<String,Repository>> it = myCache.iterator();
		while (it.hasNext()){
			Repository repo = it.next().getValue();
			if (repo.getId().equals(id)){
				return repo;
			}
		}
		return null;
	}
}
