package eu.dnetlib.repos.ehcacher;


import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.constructs.blocking.CacheEntryFactory;
import net.sf.ehcache.constructs.blocking.SelfPopulatingCache;

import org.apache.log4j.Logger;

public class CacheProvider {
	private Logger logger = Logger.getLogger(CacheProvider.class);
    private CacheManager cacheManager;
    private CacheEntryFactory updatingFactory;
    public SelfPopulatingCache selfPopulatingCache;

    public void start() throws Exception {
        try {
            Ehcache originalCache = cacheManager.getCache("doar");

            selfPopulatingCache = new SelfPopulatingCache(originalCache, updatingFactory);
        } catch (Exception e) {
            logger.error("Error initializing cache provider", e);
        }

        //cache refresh thread
        Thread updatingThread = new Thread() {
            public void run() {

                while (true) {
                    try {
                        Thread.sleep(450000);
                        logger.info("!!!!! Doing cache refresh !!!!!");
                        selfPopulatingCache.refresh();
                    } catch (Exception e) {
                        logger.error("Error while updating cache. Retry in 250000min", e);
                        try {
                            Thread.sleep(250000);
                        } catch (Exception e1) {
                            logger.error("Error while updating cache", e1);
                        }
                    }

                }
            }
        };
        updatingThread.setDaemon(true);
        updatingThread.start();

    }

    public CacheEntryFactory getUpdatingFactory() {
		return updatingFactory;
	}

	public void setUpdatingFactory(CacheEntryFactory updatingFactory) {
		this.updatingFactory = updatingFactory;
	}

	public CacheManager getCacheManager() {
		return cacheManager;
	}

	public void setCacheManager(CacheManager cacheManager) {
		this.cacheManager = cacheManager;
	}

	public Ehcache getCache(){
        return selfPopulatingCache;
    }
}