package ru.yandex.qe.cache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.config.CacheConfiguration;
import org.springframework.beans.factory.SmartFactoryBean;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.cache.ehcache.EhCacheCacheManager;

/**
 * Established by terry on 15.12.13.
 */
public class CacheFactoryBean implements SmartFactoryBean<Ehcache> {

    private CacheConfiguration cacheConfiguration;

    private EhCacheCacheManager ehCacheCacheManager;

    @Required
    public void setCacheConfiguration(CacheConfiguration cacheConfiguration) {
        this.cacheConfiguration = cacheConfiguration;
    }

    /**
     * Use only when cacheManager inherited from parent Context.
     * If cacheManager in same context circle dependency will happens.
     */
    public void setEhCacheCacheManager(EhCacheCacheManager ehCacheCacheManager) {
        this.ehCacheCacheManager = ehCacheCacheManager;
    }

    @Override
    public Ehcache getObject() throws Exception {
        Ehcache cache = new Cache(cacheConfiguration);
        if (ehCacheCacheManager != null) {
            ehCacheCacheManager.getCacheManager().addCache(cache);
        }
        return cache;
    }

    @Override
    public Class<?> getObjectType() {
        return Cache.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public boolean isPrototype() {
        return false;
    }

    @Override
    public boolean isEagerInit() {
        return true;
    }
}
