package ru.yandex.qe.cache.telemetry;

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;

import ru.yandex.monlib.metrics.registry.MetricRegistry;

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

    private final MetricRegistry metricRegistry;

    private CacheConfiguration cacheConfiguration;

    private EhCacheCacheManager ehCacheCacheManager;

    public MetricsInstrumentedCacheFactoryBean(MetricRegistry metricRegistry) {
        this.metricRegistry = metricRegistry;
    }

    @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 {
        final Ehcache cache = new MetricsInstrumentedCache(new Cache(cacheConfiguration), metricRegistry);
        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;
    }
}
